java反射示例

RAYSUNNNY發表於2014-08-24
package COM.JAVA.STUDY.REFLECT;


public class Private {
private String name = "zhangsan";
    

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

public String getName() {
return name;
}
}

package COM.JAVA.STUDY.REFLECT;


import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class PrivateTester{


public static void main(String[] args) throws Exception{
Private p = new Private();
// Private.class;
System.out.println("最早的"+p.getName());

Class> classType  = p.getClass();

Field field = classType.getDeclaredField("name");
field.setAccessible(true);
field.set(p, "lisi");
System.out.println("第一次修改的"+classType.getDeclaredMethod("getName", new Class[]{}).invoke(p, new Object[]{}));

Object obj = classType.newInstance();
Method method = classType.getDeclaredMethod("setName", new Class[]{String.class});
method.setAccessible(true);
method.invoke(obj, "第二個物件");
Private pobj = (Private) obj;
System.out.println("第二次修改的"+ pobj.getName());
}
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29227735/viewspace-1256713/,如需轉載,請註明出處,否則將追究法律責任。

相關文章