考虑这段代码

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());

    }

}


我声明p1type 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()

10-04 13:07
查看更多