Java反射

什么是反射:

  • 反射是指在程序运行期间,能够观察和修改类或者类的对象的属性和行为的特性
  • 动态获取的信息及动态调用对象的方法的功能称为反射机制
  • 通过Class文件对象,使用该文件中的成员变量,构造方法,成员方法。
  • 反射机制:在程序运行中,能够动态的获取类的信息(成员:属性 方法 内部类 构造 修饰符。。。。只要是能被编译的)

获得类相关的方法

方法 用途
asSubclass(Class<U> clazz) 把传递的类的对象转换成代表其子类的对象
Cast 把对象转换成代表类或是接口的对象
getClassLoader() 获得类的加载器
getClasses() 返回一个数组,数组中包含该类中所有公共类和接口类的对象
getDeclaredClasses() 返回一个数组,数组中包含该类中所有类和接口类的对象
forName(String className) 根据类名返回类的对象
getName() 获得类的完整路径名字
newInstance() 创建类的实例
getPackage() 获得类的包
getSimpleName() 获得类的名字
getSuperclass() 获得当前类继承的父类的名字
getInterfaces() 获得当前类实现的类或是接口

获得类中属性相关的方法

方法 用途
getField(String name) 获得某个公有的属性对象
getFields() 获得所有公有的属性对象
getDeclaredField(String name) 获得某个属性对象
getDeclaredFields() 获得所有属性对象

获得类中构造器相关的方法

方法 用途
getConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的公有构造方法
getConstructors() 获得该类的所有公有构造方法
getDeclaredConstructor(Class...<?> parameterTypes) 获得该类中与参数类型匹配的构造方法
getDeclaredConstructors() 获得该类所有构造方法

获得类中方法相关的方法

方法 用途
getMethod(String name, Class...<?> parameterTypes) 获得该类某个公有的方法
getMethods() 获得该类所有公有的方法
getDeclaredMethod(String name, Class...<?> parameterTypes) 获得该类中与参数类型匹配的构造方法
getDeclaredConstructors() 获得该类所有构造方法

在Java中的任何一个注解都离不开JDK的四个元注解

@interface
声明注解关键字
1.@Target(当前注解的使用范围)
2.@Documented(API的帮助文档)
3.@Retention(注解类型)
4.@inherited(继承)
clazz.getAnnotation()方法返回该元素的指定类型的注解

public class Test {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("ld.test.Student");
        getSuperClassAndInterfaces(clazz);
        System.out.println("
===============================");
        getClassAndModifiers(clazz);
        System.out.println("
===============================");
        getFields(clazz);
        System.out.println("
===============================");
        getMethods(clazz);
        System.out.println("
===============================");
        getConstructors(clazz);
        System.out.println("
===============================");
        getAnnotation(clazz);
    }

    // 1: 获取指定类继承的父类包括实现的接口
    public static void getSuperClassAndInterfaces(Class clazz) {
        System.out.println("该类实现的父类是:" + clazz.getSuperclass().getSimpleName());
        System.out.println("该类实现接口有:");
        Class[] interfaces = clazz.getInterfaces();
        for (Class class1 : interfaces) {
            System.out.print(class1.getSimpleName() + ",");
        }
    }

    // 2.获取类名+访问修饰符
    public static void getClassAndModifiers(Class clazz) {
        System.out.print(Modifier.toString(clazz.getModifiers()));
        System.out.print(" class");
        System.out.print(" " + clazz.getSimpleName());
    }

    // 3.获取所有成员变量
    public static void getFields(Class clazz) throws Exception {
        // 单数和复数形式的方法 getField getDeclaredField(单个) 加s获取所有
        // getField获取非私有字段 getDecalredField操作私有
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            System.out.println(field.getModifiers() + " "
                    + field.getType().getSimpleName() + " " + field.getName());
        }
        Field field = clazz.getDeclaredField("age");
        // 与通过new关键字创建的实例对象一样
        Object obj = clazz.newInstance();
        // 屏蔽字段的私有属性
        field.setAccessible(true);
        field.set(obj, 16);

        Student stu = (Student) obj;
        System.out.println(stu.getAge());
    }

    // 4.获取所有成员方法
    public static void getMethods(Class clazz) throws Exception {
        Method[] methods = clazz.getMethods();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        System.out.println("该类所有方法,包含父类:");
        for (Method method : methods) {
            System.out.println(Modifier.toString(method.getModifiers()) + " "
                    + method.getReturnType().getSimpleName() + " "
                    + method.getName() + "方法参数有:");
            for (Class classes : method.getParameterTypes()) {
                System.out.print(classes.getSimpleName() + ",");
            }
        }

        System.out.println("该类所有方法,不包含父类:");
        for (Method method : declaredMethods) {
            System.out.println(Modifier.toString(method.getModifiers()) + " "
                    + method.getReturnType().getSimpleName() + " "
                    + method.getName());
            System.out.println(method.getName() + "方法的参数有:");
            for (Class classes : method.getParameterTypes()) {
                System.out.print(classes.getSimpleName() + ",");
            }
        }
        
        Method method = clazz.getDeclaredMethod("show");
        
        Object obj = clazz.newInstance();
        
        method.invoke(obj);
    }
    
    
    //5.获取构造函数
    public static void getConstructors(Class clazz) throws Exception{
         Constructor constructor = clazz.getConstructor(String.class,int.class,String.class);
         Object obj = constructor.newInstance("小明",17,"8888");
         Student stu =(Student)obj;
         stu.show();
    }
    
    //6.注解
    public static void getAnnotation(Class clazz) throws Exception{
        StudentAnnotation annotation = (StudentAnnotation)clazz.getAnnotation(StudentAnnotation.class);
        System.out.println("学生名称:"+annotation.studentName()+",学号:"+annotation.studentNo());
        StudentAnnotation annotation2 = clazz.getDeclaredField("name").getAnnotation(StudentAnnotation.class);
        System.out.println("学生名称:"+annotation2.studentName()+",学号:"+annotation2.studentNo());
        StudentAnnotation annotation3 = clazz.getDeclaredMethod("getName").getAnnotation(StudentAnnotation.class);
        System.out.println("学生名称:"+annotation3.studentName()+",学号:"+annotation3.studentNo());
    }
    
}
原文地址:https://www.cnblogs.com/big-data-sky/p/11069215.html