Check the class name of the link containing the object in 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 it possible to? If not, please indicate the reason.

+6
source share
3 answers

If you call a.getClass() , then it always returns you an instance of the class from which this object was created. In your case, this is B , so it will return you B.class .

Now, if you want to call a method on a and get a class like A.class , you cannot do it the usual way.

One way would be to define a method in a

 public static Class<A> getType() { return A.class; } 

and then you can call a.getType() , which is equal to A.class . We use the static method here because they are not overridden.

+1
source

Chris Jetra-Jung's comment was excellent. It says:

You can not. The static type of local variables is not stored in byte code or at run time. (If this is a field, you can use reflection in the field containing the class to get the type of the field.)

See also What is the concept of erasing in generics in Java?

And http://gafter.blogspot.com/search?q=super+type+token .

+3
source

Check the class name of the link containing the object in Java

You can not.

  • There is no such thing as a link containing an object. There may be zero such links, or there may be sixten gazillion.

  • You cannot get it / them from inside a held object.

+2
source

Source: https://habr.com/ru/post/926812/


All Articles