Can we access or query the Java String intern (constant) pool?

蹲街弑〆低调 提交于 2019-11-26 21:11:03

问题


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";

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?

i.e.

StringConstantPool pool = new StringConstantPool();
System.out.println(pool.getSize()); // etc

回答1:


You cannot directly access the String intern pool.

As per Javadocs String intern pool is:

A pool of strings, initially empty, is maintained privately by the class String.

However String objects can be added to this pool using String's intern() method.

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:

  1. Declare Set<String> StringConstantPool = new HashSet<String>();
  2. call String.intern()
  3. Add returned String value into this pool StringConstantPool


来源:https://stackoverflow.com/questions/19049812/can-we-access-or-query-the-java-string-intern-constant-pool

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!