有什么办法可以查到,目前字符串池中有哪些字符串。
我能否以编程方式列出池中存在的所有字符串?
或
任何 IDE 已经有这种插件?
最佳答案
你不能从 Java 代码访问字符串池,至少不能在 Java VM 的 HotSpot 实现中。
Java 中的字符串池是使用 string interning 实现的。 .根据JLS §3.10.5 :
a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
根据 JLS §15.28 :
Compile-time constant expressions of type
String
are always "interned" so as to share unique instances, using the methodString.intern
.
String.intern
是一个本地方法,正如我们在 its declaration in OpenJDK 中看到的那样:
public native String intern();
The native code for this method来电JVM_InternString
功能。
JVM_ENTRY(jstring, JVM_InternString(JNIEnv *env, jstring str))
JVMWrapper("JVM_InternString");
JvmtiVMObjectAllocEventCollector oam;
if (str == NULL) return NULL;
oop string = JNIHandles::resolve_non_null(str);
oop result = StringTable::intern(string, CHECK_NULL);
return (jstring) JNIHandles::make_local(env, result);
JVM_END
也就是说,字符串实习是使用 native 代码实现的,并且没有 Java API 可以直接访问字符串池。但是,您可以为此目的自己编写 native 方法。
关于java - 如何检查字符串池内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24053587/