Java如何初始化String文字

Javadoc说:

String类表示字符串。 Java程序中的所有字符串文字(例如“abc”)都实现为此类的实例。

我们知道String类有两个属性,即: value[]hash ,String literal存储在String池中。

但是在放入该池之前我无法弄清楚String字面值是如何初始化的 。 好像我稍后调试字符串文字,我可以看到value[]hash以某种方式填充。

JVM是否会调用特殊指令?

如果在String.intern调用之前没有将相同的字符串放入字符串表中,则JVM会在常量池解析期间创建新的字符串文字对象。

未指定JVM如何创建和初始化此类字符串,因此只要结果对象是可以从应用程序代码访问的常规java.lang.String实例,JVM就可以执行任何操作。

对于HotSpot JVM,它不调用任何String构造函数,它只是在Heap中分配一个新对象并填写C ++代码中的字段,请参阅java_lang_String::basic_create

 Handle java_lang_String::basic_create(int length, TRAPS) { assert(initialized, "Must be initialized"); // Create the String object first, so there's a chance that the String // and the char array it points to end up in the same cache line. oop obj; obj = InstanceKlass::cast(SystemDictionary::String_klass())->allocate_instance(CHECK_NH); // Create the char array. The String object must be handlized here // because GC can happen as a result of the allocation attempt. Handle h_obj(THREAD, obj); typeArrayOop buffer; buffer = oopFactory::new_charArray(length, CHECK_NH); // Point the String at the char array obj = h_obj(); set_value(obj, buffer); // No need to zero the offset, allocation zero'ed the entire String object assert(offset(obj) == 0, "initial String offset should be zero"); //set_offset(obj, 0); set_count(obj, length); return h_obj; } 

这种新对象的hash字段初始化为零。 正确的哈希码将在第一次调用String.hashCode计算。

JVM是否会调用特殊指令?

不。没有“特殊”JVM指令可以做到这一点。

类加载基础结构很可能是使用一个String构造函数创建与文字对应的String对象; 例如String(char[])String(byte[]) 。 它将从“.class”文件中的“常量池”区域获取字符或字节。

String类的public String(char value[])上遵循断点。

编辑 :无论是谁投票:

首先,你是否按照答案尝试? 我试过了,它完全停止在那个方法中。 我试过两个不同的IDE。 其次,在该方法中分配value成员(在OP中指出)。 如果你确实尝试过,那你就得到了。 第三, hash成员(如OP中所指)在对hashCode()的调用上赋值,并为hash成员分配一个值。

显然,你没有尝试过。 如果你这样做,对断点的调查会让你在OP中得到答案:

1)如何初始化String文字

2)…不知何故填充