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.
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.
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.