Directory: The
inheritance relationship can be obtained through the Class object:
- 1.Class getSuperclass (): Get the parent class type; (single inheritance)
- 2.Class [] getInterfaces (): Get all the interfaces implemented by the current class; (multiple implementations)
- 3. Through the isAssignableFrom () method of the Class object, determine whether the Class upward transformation can be achieved.
1. Get the parent class type
public class Main {
public static void main(String[] args) throws Exception {
Class i = Integer.class;
Class n = i.getSuperclass();
System.out.println(n);
Class o = n.getSuperclass();
System.out.println(o);
System.out.println(o.getSuperclass());
}
}
Output:
class java.lang.Number
class java.lang.Object
null
Integer's parent class is Number, Number's parent class is Object, and Object's parent class is null. Except for Object, any non-interface Class must have a parent type.
2. Get all the interfaces implemented by the current class
public class Main {
public static void main(String[] args) throws Exception {
Class s = Integer.class;
Class[] is = s.getInterfaces();
for (Class i : is) {
System.out.println(i);
}
}
}
The interfaces implemented by the output Integer are:
java.lang.Comparable
java.lang.constant.Constable
java.lang.constant.ConstantDesc
3. Judging the upward transformation of Class
In non-reflective calls, when we determine whether an instance is of a certain type, under normal circumstances, use the instanceof operator:
Object n = Integer.valueOf(123);
boolean isDouble = n instanceof Double; // false
boolean isInteger = n instanceof Integer; // true
boolean isNumber = n instanceof Number; // true
boolean isSerializable = n instanceof java.io.Serializable; // true
If it is two Class instances, to determine whether an upward transformation is true, you can call isAssignableFrom ():
// Integer i = ?
Integer.class.isAssignableFrom(Integer.class); // true,因为Integer可以赋值给Integer
// Number n = ?
Number.class.isAssignableFrom(Integer.class); // true,因为Integer可以赋值给Number
// Object o = ?
Object.class.isAssignableFrom(Integer.class); // true,因为Integer可以赋值给Object
// Integer i = ?
Integer.class.isAssignableFrom(Number.class); // false,因为Number不能赋值给Integer
Blog source:
https://www.liaoxuefeng.com/wiki/1252599548343744/1264804244564000