【JAVA反射】

反射

定义

反射是一种能够在程序运行时动态访问、修改某个类中任意属性(状态)和方法(行为)的机制(包括private实例和方法)

获取class对象的三种方式

  • Class.forName(“全类名”)
  • 类名.class
  • 对象.getClass()
public class MyReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException {

        /**
         * 获取class对象的三种方式 :
         * 1. Class.forName("全类名")
         * 2. 类名.class
         * 3. 对象.getClass()
         */
        // 第一种
        // 全类名: 包名加类名
        // 最常用
        Class<?> aClass = Class.forName("com.reflect.Student");
        System.out.println(aClass);

        // 第二种
        // 一般是当做参数使用
        Class<Student> studentClass = Student.class;
        System.out.println(studentClass == aClass);

        // 第三种
        // 当已经有了这个类的对象时才可以使用
        Student student = new Student();
        Class<? extends Student> aClass1 = student.getClass();
        System.out.println(aClass1 == aClass);

    }
}

利用反射获取构造方法

Class类中用于获取构造方法的方法

  • Constructor<?> [] getConstructors(): 返回所有公共构造方法对象的数组
  • Constructor<?> [] getDeclaredConstructors(): 返回所有构造方法对象的数组
  • Constructor getConstructors(Class<?>…parameterTypes): 返回单个公共构造方法对象
  • Constructor getDeclaredConstructor(Class<?>…parameterTypes): 返回单个构造方法对象

Constructor类中用于创建对象的方法

  • T newInstance(Object… initargs): 根据指定的构造方法创建对象
  • setAccessible(boolean flag): 设置为true,表示取消访问检查
public class MyReflectDemo02 {
    public static void main(String[] args) throws Exception {
        /*
        * Constructor: 构造方法
        * Field: 字段 成员变量
        * Method: 成员方法
        * */

        /*
        * Class 类中用于获取 构造方法 的方法
        * Constructor<?> [] getConstructors()
        * Constructor<?> [] getDeclaredConstructors()
        * Constructor<T> getConstructors(Class<?>...parameterTypes)
        * Constructor<T> getDeclaredConstructor(Class<?>...parameterTypes)
        *
        * Constructor类中用于创建对象的方法
        * T newInstance(Object... initargs)
        * setAccessible(boolean flag)
        * */

        // 获取class字节码对象
        Class<?> aClass = Class.forName("com.reflect.Student");
        // 获取构造方法
        /*Constructor<?>[] constructors = aClass.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }*/

        /*Constructor<?>[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }*/

        /*Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
        System.out.println(declaredConstructor);*/

        /*Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);
        System.out.println(declaredConstructor);*/

        /*Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(int.class);
        System.out.println(declaredConstructor);*/

        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class, int.class);
        System.out.println(declaredConstructor);

        int modifiers = declaredConstructor.getModifiers();
        System.out.println(modifiers);

        for (Parameter parameter : declaredConstructor.getParameters()) {
            System.out.println(parameter);
        }

        // 临时取消权限校验
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance("张三", 23);
        System.out.println(o);

    }
}

利用反射获取成员变量

Class类中获取成员变量的方法

  • Field[] getField(): 返回所有公共成员变量对象的数组
  • Field[] getDeclaredFields(): 返回所有成员变量对象的数组
  • Field getField(String name): 返回单个公共成员变量对象
  • Field getDeclaredField(String name): 返回单个成员变量对象

Field类中用于创建对象的方法

  • void set(Object obj, Object value): 赋值
  • Object get(Object obj): 获取值
public class MyReflectDemo03 {
    public static void main(String[] args) throws Exception {
        /*
        Class类中获取成员变量的方法
        Field[] getField(): 返回所有公共成员变量对象的数组
        Field[] getDeclaredFields(): 返回所有成员变量对象的数组
        Field getField(String name): 返回单个公共成员变量对象
        Field getDeclaredField(String name): 返回单个成员变量对象

        Field类中用于创建对象的方法
        void set(Object obj, Object value): 赋值
        Object get(Object obj): 获取值
        */

        // 1. 获取class字节码对象
        Class<?> aClass = Class.forName("com.reflect.Student");
        // 2. 获取所有成员变量
        /*
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        */

        // 获取单个的成员变量
        Field gender = aClass.getField("gender");
        System.out.println(gender);

        Field name = aClass.getDeclaredField("name");
        System.out.println(name);

        // 获取权限修饰符
        int modifiers = name.getModifiers();
        System.out.println(modifiers);
        // 获取成员变量名
        String name1 = name.getName();
        System.out.println(name1);
        // 获取成员变量类型
        Class<?> type = name.getType();
        System.out.println(type);

        // 获取成员变量记录的值
        Student student = new Student("张三");
        name.setAccessible(true);
        Object o = name.get(student);
        System.out.println(o);

        // 修改成员变量的值
        name.set(student, "李四");
        System.out.println(student);
    }
}

利用反射获取成员方法

Class类中用于获取成员方法的方法

  • Method[] getMethods(): 返回所有公共成员方法对象的数组,包括继承的
  • Method[] getDeclaredMethods(): 返回所有成员方法对象的数组,不包括继承的
  • Method getMethod(String name, Class<?>…parameterTypes): 返回单个公共成员方法对象
  • Method getDeclaredMethod(String name, Class<?>…parameterTypes): 返回单个成员方法对象

Method类中用于创建对象的方法

Object invoke(Object obj, Object… args): 运行方法
参数一: 用obj对象调用该方法
参数二: 调用方法的传递的参数(非必填)
返回值: 方法的返回值(可空)

public class MyReflectDemo04 {
    public static void main(String[] args) throws Exception {

          /*
            Method[] getMethods(): 返回所有公共成员方法对象的数组,包括继承的
            Method[] getDeclaredMethods(): 返回所有成员方法对象的数组,不包括继承的
            Method getMethod(String name, Class<?>...parameterTypes): 返回单个公共成员方法对象
            Method getDeclaredMethod(String name, Class<?>...parameterTypes): 返回单个成员方法对象

            Method类中用于创建对象的方法
            Object invoke(Object obj, Object... args): 运行方法
            参数一: 用obj对象调用该方法
            参数二: 调用方法的传递的参数(非必填)
            返回值: 方法的返回值(可空)
           */

        Class<?> aClass = Class.forName("com.reflect.Student");

        // 获取所有的方法对象 包含父类中所有的公共方法
        /*Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }*/

        // 获取所有的方法对象,不包括继承的
        /*Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }*/

        // 获取指定方法
        Method method = aClass.getDeclaredMethod("eat", String.class);
        System.out.println(method);

        // 获取方法的修饰符
        /*int modifiers = method.getModifiers();
        System.out.println(modifiers);*/

        // 获取方法的名字
        String name = method.getName();
        System.out.println(name);

        // 获取方法的参数
        /*for (Parameter parameter : method.getParameters()) {
            System.out.println(parameter);
        }*/

        // 获取方法抛出的异常
        for (Class<?> exceptionType : method.getExceptionTypes()) {
            System.out.println(exceptionType);
        }

        // 方法的运行
        Student student = new Student();
        method.setAccessible(true);
        method.invoke(student, "饺子");
    }
}

反射的作用

  • 获取一个类里面所有的信息, 获取到了以后, 再执行其他的业务逻辑
  • 结合配置文件, 动态的创建对象并调用方法

案例1: 保存信息

对于任意一个对象, 都可以把对象所有的字段名和值, 保存到文件中

public class Test01 {

    public static void main(String[] args) throws Exception{

        Student student = new Student("张三", 23);
        Teacher teacher = new Teacher("李四", 3000.0);

        saveInfo(student);

    }

    /**
     * 保存对象里所有的变量名和对应的值
     * @param o
     */
    public static void saveInfo(Object o) throws Exception {

        // 创建IO流
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("E:\\java\\javase\\src\\java\\com\\reflectTest\\test01.txt"));

        Class<?> aClass = o.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
            String name = declaredField.getName();
            Object value = declaredField.get(o);
            bufferedWriter.write(name + " = " + value);
            bufferedWriter.newLine();
        }
        bufferedWriter.close();
    }
}

案例2

public class Test01 {

    public static void main(String[] args) throws Exception{

        /*
        * 反射可以跟配置文件结合的方式,动态的创建对象,并调用方法
        * */
        Properties properties = new Properties();
        properties.load(new FileInputStream("E:/java/javase/src/java/com/prop.properties"));

        String className = (String) properties.get("className");
        String methodName = (String) properties.get("methodName");

        Class<?> aClass = Class.forName(className);
        Constructor<?> constructor = aClass.getDeclaredConstructor();
        Object o = constructor.newInstance();
        Method m = aClass.getDeclaredMethod(methodName);
        m.invoke(o);

    }
}
className=com.reflectTest.Student
methodName=study
  • 18
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值