class A {
}
class B extends A {
}
class TestType {
public static void main(String args[]) {
A a = new B();
// I wish to use reference 'a' to check the Reference-Type which is 'A'.
}
}
Is is possible? If no, then please specif the reason.
getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() . Of course, this only works for reference types which all inherit from Object .
Using the instanceof Operator Similarly to the isInstance() method, the instanceof operator returns true if the object being evaluated belongs to the given type — in other words, if our object referred to on the left side of the operator passes the IS-A test for the class or interface type on the right side.
A Class is like an object constructor or a "blueprint" for creating objects. A reference is an address that indicates where an object's variables and methods are stored. You aren't actually using objects when you assign an object to a variable or pass an object to a method as an argument.
Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory.
Chris Jester-Young's comment was excellent. It says:
You can't. The static type of local variables is not retained in the bytecode, nor at runtime. (If it's a field, you can use reflection on the field's containing class to get the field's type.)
See also What is the concept of erasure in generics in Java?
And http://gafter.blogspot.com/search?q=super+type+token.
Check the class name of the reference holding an object in Java
You can't.
There is no such thing as 'the reference holding an object. There could be zero such references, or there could be sixten gazillion of them.
You can't get it/them from inside the object being held.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With