Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the class name of the reference holding an object in Java

Tags:

java

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.

like image 981
Amber Avatar asked Oct 03 '12 06:10

Amber


People also ask

How do you find the class of an object in Java?

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 .

How do you know what class an object belongs to?

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.

What is class object reference in Java?

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.

Where is object reference stored Java?

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.


2 Answers

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.

like image 107
5 revs, 2 users 45% Avatar answered Nov 01 '22 07:11

5 revs, 2 users 45%


Check the class name of the reference holding an object in Java

You can't.

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

  2. You can't get it/them from inside the object being held.

like image 30
user207421 Avatar answered Nov 01 '22 09:11

user207421