gpt4 book ai didi

java - 将parseUnsignedInt移植到java1.7

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:43:53 27 4
gpt4 key购买 nike

我使用的是 java1.8,它有 parseUnsignedInt()。我被告知我们必须使用 java1.7,因为它在系统上。我以为我可以移植 java.lang.Interger.javajava.lang.Long.javajava.lang.annotation.Native.java 函数并使用我的代码进行编译。这允许代码编译无误。运行时出现以下错误:

Exception in thread "Thread-6" java.lang.NoSuchMethodError: java.lang.Integer.parseUnsignedInt(Ljava/lang/String;)I

eclipse 调试器似乎也找不到函数。我需要做什么才能让它正常工作?

最佳答案

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 行

有关安全性的详细信息(即为什么您不能将自己的 Integer 类放入 java.lang 包中)、否决此安全性的选项以及您不应该(或更好 - 为什么不允许)的原因, 请参阅 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(...)

关于java - 将parseUnsignedInt移植到java1.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961526/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com