我们可以访问或查询Java String intern(常量)池吗? [英] Can we access or query the Java String intern (constant) pool?
问题描述
是否有办法在我们自己的程序中访问String常量池的内容?
Is there are way to access the contents of the String constant pool within our own program?
说我有一些基本代码可以做到这一点:
Say I have some basic code that does this:
String str1 = "foo";
String str2 = "bar";
现在我们的String常量池中有2个字符串浮动。有没有办法访问池并打印出上述值或获取当前池中当前包含的元素总数?
There are now 2 strings floating around in our String constant pool. Is there some way to access the pool and print out the above values or get the current total number of elements currently contained in the pool?
ie
StringConstantPool pool = new StringConstantPool();
System.out.println(pool.getSize()); // etc
推荐答案
您无法直接访问字符串实习池
。
根据 Javadocs 字符串实习池
是:
最初为空的字符串池由
类String保持私有。
但是,可以使用String的 intern()
方法将String对象添加到此池中。
However String objects can be added to this pool using String's intern()
method.
java.lang.String.intern()
返回一个实习字符串,即一个具有条目的字符串全局字符串池。如果字符串不在全局字符串池中,那么它将被添加。
java.lang.String.intern()
returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added.
以编程方式您可以遵循以下方法:
Programmatically you can follow this approach:
- 声明
设置< String> StringConstantPool = new HashSet< String>();
- call
String.intern()
- 将返回的
String
值添加到此池中StringConstantPool
- Declare
Set<String> StringConstantPool = new HashSet<String>();
- call
String.intern()
- Add returned
String
value into this poolStringConstantPool
这篇关于我们可以访问或查询Java String intern(常量)池吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!