有没有办法在我们自己的程序中访问字符串常量池的内容?
假设我有一些基本代码可以做到这一点:
String str1 = "foo";
String str2 = "bar";
现在有 2 个字符串在我们的字符串常量池中浮动。是否有某种方法可以访问池并打印出上述值或获取当前包含在池中的元素总数?
IE
StringConstantPool pool = new StringConstantPool();
System.out.println(pool.getSize()); // etc
您不能直接访问String intern pool.
根据Javadocs String intern pool是:
一个字符串池,最初是空的,由 String 类私下维护。
intern()但是,可以使用 String 的方法将 String 对象添加到此池中。
java.lang.String.intern()返回一个实习字符串,即在全局字符串池中有一个条目的字符串。如果字符串尚未在全局字符串池中,则将添加该字符串。
以编程方式,您可以遵循以下方法:
Set<String> StringConstantPool = new HashSet<String>();String.intern()String值添加到此池中StringConstantPool