简体   繁体   中英

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

Consider this code

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

    }

}

I declare p1 to be of type Parent , but assign it to a Child instance . when I do getClass().getName() I get Child as output. how can I get the declared type which is Parent in this case?

EDIT: This does not work in all cases: getClass().getSuperclass().getName()

consider this code

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

    }

}

This ouputs Child but it must be Parent

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

I thing there is no other method to find than just looping over superclasses.

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

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

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

However never do this, this is very bad design

edit:

In your extended version you will need a loop

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

To get the immediate superclass

p1.getClass().getSuperClass();

However, in the event you are declaring an interface, you might use

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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