繁体   English   中英

如何在Java运行时中获取变量的声明类型?

[英]how to get the declared type of a variable in runtime in Java?

考虑这段代码

class Parent {

}

class Child extends Parent {

}

public class InheritenceExample {

    public static void main(String[] args){
        Parent p1 = new Child();
        System.out.println("the class name is "+ p1.getClass().getName());

    }

}

我将p1声明为type Parent ,但将其分配给Child instance 当我执行getClass().getName()我得到Child作为输出。 在这种情况下,如何获取声明的类型为Parent类型?

编辑:这并非在所有情况下都起作用: getClass().getSuperclass().getName()

考虑这个代码

class Parent {

}

class Child extends Parent {

}

class GrandChild extends Child {


}

public class InheritenceExample {

    public static void main(String[] args){
        Parent p1 = new GrandChild();
        System.out.println("the class name is "+ p1.getClass().getSuperclass().getName());

    }

}

这个输出是Child但必须是Parent

也许尝试使用getClass().getSuperclass()

我觉得除了循环超类之外,没有其他方法可以找到。

Class<?> c = p1.getClass();

while (c.getSuperclass() != Object.class) {
  c = c.getSuperclass();
}

System.out.println("the class name is "+ c.getClass());
   getClass().getSuperclass().getName()

但是永远不要这样做,这是非常糟糕的设计

编辑:

在扩展版本中,您将需要循环

Parent superClass = p1.getClass();
while (superClass.getSuperclass() != Object.class) {
    superClass = superClass.getSuperclass();
}
superClass.getName();

获得直接超类

p1.getClass().getSuperClass();

但是,如果您声明一个接口,则可以使用

        Class[] interfaces = p1.getInterfaces();
        if(interfaces != null){
            for(Class i : interfaces){
                System.out.println(i);
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM