62,614
社区成员
发帖
与我相关
我的任务
分享
class Student
{
public Student(){}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
private String name;
private int age;
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
public class Reflect {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
Student s =new Student("Sam",23);
Class c = s.getClass();
Field f= c.getDeclaredField("name");
System.out.println(f);
f.setAccessible(true);
Object obj = f.get(s);
System.out.println(obj);
Field f1 =c.getDeclaredField("age");
f1.setAccessible(true);
Object obj1= f1.get(s);
System.out.println(obj1);
f.set(obj,"huhu");
System.out.println(obj);
}
}