Say I have a class that extends java.lang.Object as follows:
package pack;
public class Person {
}
And the following three instances:
Object one = new Object();
Object two = new Person();
Person three = new Person();
In order to determine the runtime-type, I just need invoke the getClass() method on the instances as follows:
System.out.println("One runtime-type : " + one.getClass());
System.out.println("Two runtime-type : " + two.getClass());
System.out.println("Three runtime-type : " + three.getClass());
Which outputs:
One runtime-type : class java.lang.Object
Two runtime-type : class pack.Person
Three runtime-type : class pack.Person
Now my question is how do I programmatically determine the static/compile-type of the instances above?
By static/compile-type I mean the type "on the left". It would output:
One compile-type : class java.lang.Object
Two compile-type : class java.lang.Object
Three compile-type : class pack.Person
You didn't specify when you want to find out about the compile time types. From your sample output I assume you want to print out the compile-time types at runtime.
This is not possible, (update:) unless you do it manually, knowing all types you want to use beforehand.
If you know that you will be using only Object and Person classes, you can try the code below. You need to define a method for each of the used classes and the compiler is smart enough to use the best matching method.
This prints out:
Note that this method may break if you want to apply it to interfaces, where you may run into situation when the compiler cannot decide which method to use.
Original answer:
You are basically asking what are the types of the variables in your source code. The only thing left from your source code at runtime is the bytecode produced by Java compiler. This bytecode doesn't include any information about the types of your variables.
Here is what the bytecode may look like for your source code:
You can see that except for the invocation of Person's constructor, there is no reference to type Person, therefore the information that e.g. variable
three
was of type Person is lost. Also, Java doesn't have any built-in operator that you could use to capture the type of the variable at compile time.