通过反射来修改,反射还能实现swap(int a,int b)
package zhengze; import java.lang.reflect.Field; import java.util.logging.FileHandler; public class Person { private int id; private String name; private int sex; Person(int a,String b, int c) { id = a; name = b; sex = c; } public void setName(String name) { this.name = name; } public void setId(int id) { this.id = id; } public void setSex(int sex) { this.sex = sex; } public String getName() { return name; } public int getId() { return id; } public int getSex() { return sex; } @Override public String toString() { return super.toString()+" "+name; } public static void main(String[] args) throws Exception{ Person person = new Person(1,"liy",1); Class c = person.getClass(); System.out.println(c); Field f = c.getDeclaredField("name"); System.out.println(f.getName()); f.setAccessible(true); f.set(person,"liyming"); System.out.println(person); } }