检查包含Java中对象的引用的类名

Amb*_*ber 6 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'.
   }
}
Run Code Online (Sandbox Code Playgroud)

有可能吗?如果没有,那么请说明原因.

Ami*_*nde 1

如果您调用,a.getClass()那么它将始终返回创建该对象的类的实例。就你而言,B它会返回你B.class

现在,如果您想调用方法a并获取类,A.class那么您将无法以正常方式执行此操作。

一种出路是定义方法A

public static Class<A> getType() {
        return A.class;
    }
Run Code Online (Sandbox Code Playgroud)

然后你可以调用a.getType()which is A.class。我们在这里使用静态方法,因为它们没有被重写。