http://my.oschina.net/wangyumin/blog/387627
The last reflection method calls the private member, and the method is recently encapsulated two times.
Reflectutil.java
Partial code slightly/** * Invoking method Plus * * @param object Java Object * @param methodName methods Name * @param args Entry Object * @return Execution Result Object */public static object Invokemethodplus (Object object, String METHODN Ame, 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]; Original type fix 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; }
Comparison of new and old methods:
// 老方法: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); }
For more detailed code, see: https://github.com/wangym/java-common/
Test class private Members with Java Reflection (new)