通过Java反射的获取私有成员变量,调用私有方法

Java的反射工具很强大,有句著名的话:No reflection ,no frameworks.

纳整理一个小工具类:

/**
 * @Author 落叶飞翔的蜗牛
 * @Date 2018/3/10
 * @Description
 */
public class ReflectionUtils {

    /**
     * 获取私有成员变量的值
     * @param instance
     * @param filedName
     * @return
     */
    public static Object getPrivateField(Object instance, String filedName) throws NoSuchFieldException, IllegalAccessException {
        Field field = instance.getClass().getDeclaredField(filedName);
        field.setAccessible(true);
        return field.get(instance);
    }

    /**
     * 设置私有成员的值
     * @param instance
     * @param fieldName
     * @param value
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void setPrivateField(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = instance.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(instance, value);
    }

    /**
     * 访问私有方法
     * @param instance
     * @param methodName
     * @param classes
     * @param objects
     * @return
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object invokePrivateMethod(Object instance, String methodName, Class[] classes, String objects) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = instance.getClass().getDeclaredMethod(methodName, classes);
        method.setAccessible(true);
        return method.invoke(instance, objects);
    }
}

写个简单的单元测试如下:

/**
 * @Author 落叶飞翔的蜗牛
 * @Date 2018/3/10
 * @Description
 */
@RunWith(SpringRunner.class)
public class ReflectionUtilsTest {

    private String name;

    private void setName(String name) {
        this.name = name;
    }

    @Test
    public void test() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        ReflectionUtilsTest reflectionUtilsTest = new ReflectionUtilsTest();
        //访问私有属性
        System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
        //设置私有属性
        ReflectionUtils.setPrivateField(reflectionUtilsTest, "name", "张三");
        System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
        //调用私有方法
        ReflectionUtils.invokePrivateMethod(reflectionUtilsTest, "setName", new Class[]{String.class}, "李四");
        System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
    }
}

输出结果如下:

name = null
name = 张三
name = 李四

猜你喜欢

转载自blog.csdn.net/shixuetanlang/article/details/79512356