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

Amber
  • 1,229
  • 9
  • 29
  • 7
    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.) – C. K. Young Oct 03 '12 at 06:53
  • 1
    @ChrisJester-Young You should make that an answer instead of a comment. – Jesper Oct 03 '12 at 07:00

3 Answers3

3

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.

Community
  • 1
  • 1
gobernador
  • 5,659
  • 3
  • 32
  • 51
2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

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

Now if you want to call method on a and get class as A.class then you will not able to do it normal way.

One way out would be define method in A

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

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

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72