http://my.oschina.net/wangyumin/blog/387627
续上篇反射方式调用私有成员,最近对该方法进行了二次封装。
ReflectUtil.java
//部份代码略
/**
* Invoking method plus
*
* @param object Java object
* @param methodName 方法名称
* @param args 入参对象
* @return 执行结果对象
*/
public static Object invokeMethodPlus(Object object, String methodName, Object... args) {
Object result = null;
if (null != args) {
int length = args.length;
Class[] types = new Class[length];
Object[] values = new Object[length];
for (int i = 0; i < length; i++) {
types[i] = args[i].getClass();
values[i] = args[i];
// 原始类型修补
Field[] fields = types[i].getFields();
for (Field field : fields) {
if ("TYPE".equalsIgnoreCase(field.getName())) {
try {
types[i] = (Class) field.get(null);
} catch (IllegalAccessException e) {
LogUtil.error(e);
}
}
}
}
result = invokeMethod(object, methodName, types, values);
}
return result;
}
新老方法对比:
// 老方法:
Object invokeMethod(Object object, String methodName, Class[] parameterTypes, Object[] args)
// 新方法(类型与入参不必分离由方法内部适配):
Object invokeMethodPlus(Object object, String methodName, Object... args)
ReflectUtilTest.java
//部份代码略
@Test
public void testInvokeMethodPlusForInt() throws Exception {
int age = 18;
Person person = new Person();
String howOldAreYou = (String) ReflectUtil.invokeMethodPlus(person, "howOldAreYou", age);
Assert.assertEquals(Person.howOldAreYou + age, howOldAreYou);
}
@Test
public void testInvokeMethodPlusForString() throws Exception {
String name = "xuanyin";
Person person = new Person();
ReflectUtil.invokeMethodPlus(person, "setName", name);
String whatIsYourName = (String) ReflectUtil.invokeMethodPlus(person, "whatIsYourName");
Assert.assertEquals(Person.whatIsYourName + name, whatIsYourName);
}
更详细代码请参见:https://github.com/wangym/java-common/
时间: 2024-09-29 10:17:17