反射的使用
反射的使用
拿到此类的接口/包/注解
import java.lang.annotation.Annotation;
@Deprecated
public class demo6 implements Runnable {
@Override
public void run() {
}
public static void main(String[] args) {
Class demo6Class = demo6.class;
// 拿到接口
Class[] interfaces = demo6Class.getInterfaces();
for (Class anInterface : interfaces) {
System.out.println("接口有:" + anInterface);
}
// 拿到包
Package aPackage = demo6Class.getPackage();
System.out.println("包 => " + aPackage);
// 拿到注解
Annotation[] annotation = demo6Class.getAnnotations();
for (Annotation annotation1 : annotation) {
System.out.println("注解 => " + annotation1);
}
}
}
拿到父类的泛型
/*
* 通过反射拿到父类的泛型
* */
public class Demo {
public static void main(String[] args) {
Class demo01Class = Demo01.class;
ParameterizedType parameterizedType = (ParameterizedType) demo01Class.getGenericSuperclass();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
System.out.println(actualTypeArguments[0]);
}
}
class Demo01 extends Demo02<Integer> {
}
class Demo02<T> {
}