我正在使用具有parseUnsignedInt()
的java1.8。有人告诉我,我们必须使用java1.7
,因为这已经在系统上了。我以为我可以只移植java.lang.Interger.java
,java.lang.Long.java
和java.lang.annotation.Native.java
函数并用我的代码进行编译。这使代码可以正确编译。当我运行时,出现以下错误:
线程“ Thread-6”中的异常java.lang.NoSuchMethodError:java.lang.Integer.parseUnsignedInt(Ljava / lang / String;)I
eclipse调试器似乎也找不到该函数。我该怎么做才能使它正常工作?
答案 0 :(得分:1)
parseUnsignedInt方法是Java 1.8引入的,因为它已在其Javadoc中记录(请注意 @since 1.8 ):
/**
* Parses the string argument as an unsigned decimal integer. The
* characters in the string must all be decimal digits, except
* that the first character may be an an ASCII plus sign {@code
* '+'} ({@code '\u005Cu002B'}). The resulting integer value
* is returned, exactly as if the argument and the radix 10 were
* given as arguments to the {@link
* #parseUnsignedInt(java.lang.String, int)} method.
*
* @param s a {@code String} containing the unsigned {@code int}
* representation to be parsed
* @return the unsigned integer value represented by the argument in decimal.
* @throws NumberFormatException if the string does not contain a
* parsable unsigned integer.
* @since 1.8
*/
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s, 10);
}
但是JDK也包含源代码,因此您可以在自己的类中编写自己的parseUnsignedInt方法,如果Java 8许可证允许,则类似于Java 8中包含的实现。
请参见http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/Integer.java 661行ff
有关安全性的详细信息(即,为什么不能在java.lang包中放置自己的Integer类),否决该安全性的选项以及不应该这样做的原因(或更好的原因-不允许这样做) ,请参阅Why I am able to re-create java.lang package and classes?
中的选定答案因此,您将必须在自己的程序包中实现自己的类:
package com.yourname;
/*
* Contains code from OpenJDK Java8, Copyright (c) 1994, 2013, Oracle and/or its affiliates.
* TODO add more info from Oracle class comment here.
*/
public class IntCompatUtilities {
public static int parseUnsignedInt(String s) throws NumberFormatException {
return parseUnsignedInt(s,10);
}
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
//TODO content from OpenJDK 8's Integer.parseUnsignedInt(String,int) here.
//instead of return parseInt(s, radix); change to return Integer.parseInt(s, radix);
//instead of throw NumberFormatException.forInputString(s); throw new NumberFormatException(...)
}
}
然后,让所有呼叫者都呼叫com.yourname.IntCompatUtilities.parseUnsignedInt(...)