String s1 == String s2 (true) but FieldOffset is different

后端 未结 4 1163
生来不讨喜
生来不讨喜 2021-02-08 13:47

As I am studying java, I have learned that the proper way to compare 2 Strings is to use equals and not \"==\". This line

static String s1 = \"a\";
static String s2          


        
4条回答
  •  我寻月下人不归
    2021-02-08 14:44

    I think you're confused on what staticFieldOffset is returning. It's returning the offset of the pointer to the String instance, not the address of the String itself. Because there are two fields, they have different offsets: ie, two pointers, which happen to have the same value.

    A close reading of the Unsafe javadoc shows this:

    Report the location of a given field in the storage allocation of its class. Do not expect to perform any sort of arithmetic on this offset; it is just a cookie which is passed to the unsafe heap memory accessors.

    In other words, if you know where the actual Class instance is in memory, then you could add the offset returned by this method to that base address, and the result would be the location in memory where you could find the value of the pointer to the String.

提交回复
热议问题