tags:

views:

132

answers:

3

Hi All, How does jvm know what class an object is an instance of at runtime. I know we can use the getClass method to get the class name but how does the getClass method work? Thx, Praveen.

+1  A: 

I don't know the specifics of the JVM, but in most object oriented language + runtime systems (Delphi, C++, .NET), a hidden field is added to the object instance data which points to the object instance's type information.

You have to be careful of this when mapping an object instance directly onto an external data structure because the hidden type info or virtual method table pointer in the object instance data will throw off alignment with the fields in the external data structure.

You can usually see this artifact by looking at the size of the object instance. Sizeof() or equivalent. An object with no declared fields will still have a memory footprint greater than zero. That's where the type info magic comes from.

dthorpe
+1  A: 

The answer? Magic!

No, seriously, it's implementation defined, and an implementation of the JVM need not use a single simple technique, like storing the class as a reference in a field at a constant offset in the instance's data. All it need do is make sure the getClass method observably works as documented. For example, with escape analysis, a JVM may allocate an instance statically on the heap, because it knows the instance doesn't outlive the stack frame. In this case, it may elect to turn a getClass() call into a direct load of the Class instance, rather than a method call at all! Similarly, since getClass() is logically a virtual method (I know it's final but its return value is constant across all instances of a class from any given class loader but different for each distinct class, as if it were a virtual that returned a constant value), it may undergo similar optimizations to inline caching.

Barry Kelly
A: 

http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html

Romain Hippeau
The class file format is a serialization format for the definition of the class. It doesn't really relate to how the JVM joins any given object instance with a `Class` object instance through the `getClass()` method.
Barry Kelly
It does explain what the JVM does when it creates an Object. Part of it is to have the Class Meta-Info available
Romain Hippeau
Actually, it doesn't. The JVM spec only defines what appears to happen. For example, it defines the meaning of code in terms of a stack machine; but there need not exist any actual stack machine with the same logical slots, the same logical values pushed and popped, at runtime. Instead, a JVM may elect to JIT everything, and not interpret. But this question relates to how does a JVM know at runtime, when that stack may not exist. And the only answer is that it's entirely up to the JVM, so long as it appears to work as documented.
Barry Kelly