Java反射技术--获取私有属性和方法

1、首先,创建一个类,部分属性和方法设置为private。

package com.example.demo.utils;

/**
 * @Author HL
 * @Date 2021年3月20日
 */
public class Person {
    private String id = "10";
    private String name = "张三";

    private String getId() {
        return id;
    }

    private String getName() {
        return name;
    }

    public String getInfo() {
        return id + ", " + name;
    }
}

2、再创建一个类,利用Java反射机制调用私有属性和方法。

package com.example.demo.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 测试Java反射技术
 * @Author HL
 * @Date 2021年3月20日
 */
public class ReflectTest {
    public static void main(String[] args) {
        reflectMethod();
    }

    /**
     * 反射方法获取私有属性及方法
     *
     * @Author HL
     * @Date 2021年3月20日
     */
    public static void reflectMethod() {
        try {
            // 获得Person类
            Class c1 = Person.class;
            Person p1 = (Person) c1.newInstance();
            // 获得Person所有属性
            Field[] fields = c1.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                // 将目标属性设置为可以访问
                fields[i].setAccessible(true);
                System.out.println("修改前" + fields[i].getName() + ": " + fields[i].get(p1));
                // 给属性重新赋值
                fields[i].set(p1, null);
                System.out.println("修改后" + fields[i].getName() + ": " + fields[i].get(p1));
            }
            // 获得Person所有方法
            Method[] methods = c1.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                // 将目标方法设置为可以访问
                methods[i].setAccessible(true);
                // 输出所有方法名称
                System.out.println("方法" + methods[i].getName());
            }
            // 获得指定名称的方法
            Method method = c1.getDeclaredMethod("getInfo");
            method.setAccessible(true);
            System.out.println("getInfo方法返回值:" + method.invoke(p1));

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }
}

3、代码执行结果如下。

修改前id: 10
修改后id: null
修改前name: 张三
修改后name: null
方法getName
方法getId
方法getInfo
getInfo方法返回值:null, null

Process finished with exit code 0