继承关系
获取继承关系
反射不仅可以用来获取方法,字段,构造方法。还可以用来获取它的继承关系,便于我们对类之间的联系有更清晰的了解。
public class Main {
public static void main(String[] args) throws Exception {
Class<? extends Student> sClass = Student.class;
Class<?> superclass = sClass.getSuperclass();
System.out.println(superclass);
System.out.println(superclass.getSuperclass());
}
}
class Student{
public Student(){}
}
输出及分析
输出:
class java.lang.Object
null
分析:
我们知道,Java任何类都有一个父类Object, 这是最高级别的父类,当我们尝试获取Object的父类时,得到的结果为null 。
grtSuperClass()方法
该方法用于获得类的父类,因为Java是单继承的,所以不会出现多个父类的情况。
如果需要获得父类的父类,不断调用getSuperClass()即可。
获得父类的大Class之后,就可以调用父类的Class方法,去获得属性,字段,构造函数之类的操作。
获得interface
其实实现interface的类也能看作是interface的子类,它与子类的行为很相似。
获得interface的方法:getInterfaces(),该方法返回一个Class列表, 这样我们就可以获得该类实现的所有接口了。
注意:该方法只能获得该类的接口,而不能获得父类的。
public class Main {
public static void main(String[] args) throws Exception {
Class<Integer> integerClass = Integer.class;
AnnotatedType[] annotatedInterfaces = integerClass.getAnnotatedInterfaces();
Class<?>[] interfaces = integerClass.getInterfaces();
for (Class<?> inter : interfaces) {
System.out.println(inter);
}
}
}
interface java.lang.Comparable
interface java.lang.constant.Constable
interface java.lang.constant.ConstantDesc
拿到接口之后干嘛,就获得一个列表?
接口类使用
拿到接口之后, 我们可以获取接口上的注解
我们可以获取接口上的注解,判断类的特定行为:
for (AnnotatedInterface ai : clazz.getAnnotatedInterfaces()) {
if (ai.getType() == MyInterface.class) {
Annotation[] annotations = ai.getAnnotations();
if (annotations[0] instanceof Transactional) {
// 实现 MyInterface 接口,同时标记为事务处理
}
}
}
比如mybatis-plus的mapper层,它会去帮我们默认实现映射层,我们要让它找到该接口类,自然需要给它打标识,比如@Mapper。这样sprongboot扫描到该注解后自动为其添加实现方法喽,我们只用在service层继承它的实现类serviceImpl。