- import java.lang.reflect.Field;
- public class ReflectFinal {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception {
- Person p1 = new Person("郭宁",23);
- System.out.println(p1.name+" "+p1.getAge());
- Field field = p1.getClass().getDeclaredField("age");
- field.setAccessible(true);
- field.set(p1, 99);
- System.out.println(p1.name+" "+p1.getAge());
- }
- }
- class Person{
- private final int age;
- public String name="我是初始化的";
-
- Person(String name,int age){
- this.name=name;
- this.age = age;
- }
- public int getAge(){return age;}
- }
复制代码 结果:
郭宁 23
郭宁 99 |