[英]Is there a way to access package-private String.isLatin1() from java.util package using jdk.internal.access.SharedSecrets?
I'm trying to access String.isLatin1()
which is declared (as of JDK 14) as我正在尝试访问声明为(从 JDK 14 开始)的
String.isLatin1()
boolean isLatin1() {
return COMPACT_STRINGS && coder == LATIN1;
}
I can do this with reflection我可以用反射来做到这一点
Method isLatin1 = String.class.getDeclaredMethod("isLatin1");
isLatin1.setAccessible(true);
isLatin1.invoke(""); //true
but I wonder whether I can do the same with SharedSecrets
?但我想知道我是否可以对
SharedSecrets
做同样的事情?
I've tried我试过了
SharedSecrets.getJavaLangAccess().getDeclaredPublicMethods(String.class, "isLatin1");
but for obvious reason it returns an empty list.但出于显而易见的原因,它返回一个空列表。 Also I've tried to utilize
jdk.internal.access.JavaLangReflectAccess
available from SharedSecredts
, but it doesn't have any suitable method.此外,我一直试图利用
jdk.internal.access.JavaLangReflectAccess
从SharedSecredts
,但它没有任何合适的方法。
It is not going to work.这是行不通的。 The shared secrets mechanism provides a way to specific package private methods.
共享秘密机制提供了一种特定的封装私有方法的方法。 If you look at the source code, you will see that there is an "access" interface that exposes a fixed set of methods.
如果您查看源代码,您会看到有一个“访问”接口,它公开了一组固定的方法。 The shared secrets interface for the
java.lang
package exposes some methods for getting a string's internal byte array without copying it. java.lang
包的共享机密接口公开了一些无需复制即可获取字符串内部字节数组的方法。 But it doesn't provide a method that does what you want.但它没有提供一种方法来做你想要的。
Furthermore, the isLatin1()
method that you are trying to access is private
rather than package private, so it cannot be exposed anyway ... unless you change that.此外,您尝试访问的
isLatin1()
方法是private
而不是包私有的,因此无论如何它都不能公开……除非您更改它。
In short, you can't use SharedSecrets
for this unless you are prepared to modify the OpenJDK source code and build your own JVM .简而言之,除非您准备修改 OpenJDK 源代码并构建您自己的 JVM,否则您不能为此使用
SharedSecrets
。 It might be acceptable to do that as an experiment, but there are lots of red flags for production use.将其作为实验进行可能是可以接受的,但是在生产使用中存在很多危险信号。
Use reflection.使用反射。 It is more practical ... modulo that you risk causing future portability problems for your application.
它更实用......取模您可能会为您的应用程序带来未来的可移植性问题。 (Consider that the internal representation of
String
have changed 2 or 3 times so far since Java 1.1. It could happen again.) (考虑到内部表示
String
,因为Java 1.1中已经改变了2〜3次,到目前为止,它可能再次发生。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.