how can i get the address of an instance of a string class using java?is there any way to obtain this? [duplicate]
I would like others to explain that how can i get the address o开发者_开发技巧f an instance of string class in java?Is there any way to obtain this?I tried this but not getting the way to solve the problem?
I doubt you can reliably get the address of an object in general, and you are probably on the wrong track if you think you need to, although the link posted by Farmor gives one technique using the aptly named Unsafe
class.
You can also use System.identityHashCode
to get "the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode()" as explained by the API Javadoc. This in turn is "typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java(TM) programming language."
You can obtain the absolute address using JNI or using the Unsafe class.
However both are a BAD idea as the address is next to useless. The multi-threaded GC can move the object at any time. i.e. it can be invalid as soon as you get it.
You can copy/change the address but its a great way to cause the JVM to crash at random points in an untraceable way. i.e. the GC looks at it and the JVM dies at some random point of time later.
Do you mean the physical address in memory? If so, then no - Java manages an abstraction of the memory for you.
(What is it you're trying to achieve? It's likely that there's a much more idiomatic way of doing this in Java; you shouldn't ever need the memory addresses directly. In a logical sense, a reference to a string is the "address" of that object.)
The Java language does not support the concept of memory addresses since the runtime does all memory management for you.
Conceivably you could do some trickery with JNI but I don't think it would be reliable at all as there is no any guarantee that the address of any object won't change arbitrarily, e.g. with garbage collector sweeps.
You can't get the memory address of an object in pure Java.
And even if you could, you wouldn't be able to use it reliably. The GC may run at any moment and move the object, leaving your pointer pointing at empty space, at the middle of some other object or at an object with a different type.
If you have inside knowledge of some of the (notionally) opaque JNI types, you should be able to extract an address. And I also believe that there is a sun.java.Unsafe
class that may be able to do this ... though you need to knobble the classloader to use it.
The logical memory address you can obtain.
The absolute physical memory address you can't obtain.
精彩评论