Let\'s say we have a class:
class Class1
{
int i = 1;
}
and we have a variable:
Class1 ob1 = new Class1();
Every java object reference knows its class at runtime; this so-called "run-time type information" is used in code like this:
if (obj instanceof class1) {
// true!
}
You can also access the class of an object through obj.getClass()
. This will return class1.class
, an object of class Class
. See the Object.getClass method.
(Note that if your class is parameterized, as class1
, the type of T
will not be stored at runtime, due to "erasure".)
I don't know whether the class information is stored with the pointer or with the data; it's probably implementation-specific in the jvm; but it hardly matters from a practical standpoint. (So either answer 1 or 2, or both, is "yes").
The answer to 3 is that, as far as a java programmer is concerned, the run-time type information is encapsulated in an object of class Class
. Under the covers, a JVM may implement this in one way or another.