J
J
Jake Taylor2020-07-04 18:17:19
Java
Jake Taylor, 2020-07-04 18:17:19

How to get the address of a reference to an object of type String in Java?

There is a string: How to get the value of the address, which is stored in the variable s1, in a string pool in Java?
String s1 = "Hello world!";

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-07-04
@n199a

Not by standard means. With the help of dirty hacks, it is possible, but not the fact that they will always work in all JVMs:

class AddressExtractor {
    public long pointerValue;
}

public class DirtyHack {
    public static void main(String[] args) throws Exception {
        AddressExtractor addressExtractor = new AddressExtractor();
        Class<? extends AddressExtractor> clazz = addressExtractor.getClass();
        Field field = clazz.getDeclaredField("pointerValue");
        Field type = Field.class.getDeclaredField("type");
        AccessibleObject.setAccessible(new AccessibleObject[]{field, type}, true);
        type.set(field, Object.class);
 
        String s = "test";
        field.set(addressExtractor, s);
        System.out.println(Long.toHexString(addressExtractor.pointerValue));
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question