当我正在学习
java时,我已经知道,比较2个字符串的正确方法是使用equals而不是“==”.这一行
static String s1 = "a";
static String s2 = "a";
System.out.println(s1 == s2);
将输出true,因为jvm似乎优化了这个代码,以便它们实际上指向同一个地址.我试图证明这是使用我在这里发现的一个伟大的文章
但地址似乎不一样.我失踪了什么
import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class SomeClass {
static String s1 = "a";
static String s2 = "a";
public static void main (String args[]) throws Exception {
System.out.println(s1 == s2); //true
Unsafe unsafe = getUnsafeInstance();
Field s1Field = SomeClass.class.getDeclaredField("s1");
System.out.println(unsafe.staticFieldOffset(s1Field)); //600
Field s2Field = SomeClass.class.getDeclaredField("s2");
System.out.println(unsafe.staticFieldOffset(s2Field)); //604
}
private static Unsafe getUnsafeInstance() throws SecurityException,NoSuchFieldException,IllegalArgumentException,IllegalAccessException {
Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeInstance.setAccessible(true);
return (Unsafe) theUnsafeInstance.get(Unsafe.class);
}
}