java 反射私有变量赋值_通过反射,操作私有成员变量(取/赋值),调用私有方法...

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

工作中直到涉及到UT,才体会到它的重要性,现归纳整理一个小例子:

反射工具类:import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class ReflectionUtil {

/***

* 获取私有成员变量的值

*

*/

public static Object getValue(Object instance, String fieldName)

throws IllegalAccessException, NoSuchFieldException {

Field field = instance.getClass().getDeclaredField(fieldName);

field.setAccessible(true); // 参数值为true,禁止访问控制检查

return field.get(instance);

}

/***

* 设置私有成员变量的值

*

*/

public static void setValue(Object instance, String fileName, Object value)

throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

Field field = instance.getClass().getDeclaredField(fileName);

field.setAccessible(true);

field.set(instance, value);

}

/***

* 访问私有方法

*

*/

public static Object callMethod(Object instance, String methodName, Class[] classes, Object[] objects)

throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,

InvocationTargetException {

Method method = instance.getClass().getDeclaredMethod(methodName, classes);

method.setAccessible(true);

return method.invoke(instance, objects);

}

}package com.test;

public class Person {

private String name;

private int age;

public Person(String name, int age) {

this.name = name;

this.age = age;

}

private String getInfo(String str, int num) {

return str + num + " apples";

}

}import com.test.Person;

public class ReflectTest {

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

Person person = new Person("jack", 25);

// test get private value

System.out.println("jack's name:" + ReflectionUtil.getValue(person, "name"));

System.out.println("jack's age:" + ReflectionUtil.getValue(person, "age"));

// test set private value

ReflectionUtil.setValue(person, "name", "jason");

ReflectionUtil.setValue(person, "age", 10);

System.out.println("jack's name:" + ReflectionUtil.getValue(person, "name"));

System.out.println("jack's age:" + ReflectionUtil.getValue(person, "age"));

// test call private method

String result = (String) ReflectionUtil.callMethod(person, "getInfo", new Class[] { String.class, int.class },

new Object[] { "I hava ", 4 });

System.out.println("result: " + result);

}

}结果:

jack's name:jack

jack's age:25

jack's name:jason

jack's age:10

result: I hava 4 apples

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值