ToBeReflact.java
package com.testcases.reflaction; /** * Created by shiyanghuang on 16/3/2. */ public class ToBeReflact { private String name; ToBeReflact() { this.name = "Default"; } ToBeReflact(String name) { this.name = name; } private void setName(String name) { this.name = name; } private String getName() { return this.name; } }
ReflactionClass.java
package com.testcases.reflaction; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by shiyanghuang on 16/3/2. */ public class ReflactionClass { public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { Class classtype = ToBeReflact.class; Object toBeReflact = classtype.newInstance(); Method setNameMethod = classtype.getDeclaredMethod("setName", new Class[] {String.class}); setNameMethod.setAccessible(true); Object invoke1 = setNameMethod.invoke(toBeReflact, "qwer"); Method getNameMethod = classtype.getDeclaredMethod("getName", null); getNameMethod.setAccessible(true); Object invoke2 = getNameMethod.invoke(toBeReflact, null); System.out.print(invoke2); } }
参考:
http://stackoverflow.com/questions/880365/any-way-to-invoke-a-private-method
http://blog.csdn.net/cuiran/article/details/5302074
One Response so far.