本帖最后由 李志卫 于 2013-3-16 23:52 编辑
- import java.lang.reflect.Field;
- public class Test9{
- public final int x = 100;
- public int Method(Test9 t1,Test9 t2) throws Exception{
- int i = t1.x;
- System.out.println("i's value is "+i);
- changeX(t1);
- System.out.println("i2's value is "+t1.x);
- int j = t2.x;
- System.out.println("j's value is "+j);
- return j - i;
- }
- public static void changeX(Test9 t1) throws Exception{
- Class clazz = t1.getClass();
- Field fieldX = clazz.getDeclaredField("x");
- fieldX.setAccessible(true);
- fieldX.setInt(t1, 300);
- System.out.println("fieldX's vlaue is "+fieldX.getInt(t1));
- }
- public int test() throws Exception{
- return Method(this,this);
- }
- public static void main(String[] args) throws Exception{
- Test9 t1 = new Test9();
- System.out.println(t1.test());
- }
- }
复制代码结果是
i's value is 100 fieldX's vlaue is 300 i2's value is 100 j's value is 100 0 - import java.lang.reflect.Field;
- public class Test9{
- public final int x;
- public Test9()
- {
- x = 100;
- }
- public int Method(Test9 t1,Test9 t2) throws Exception{
- int i = t1.x;
- System.out.println("i's value is "+i);
- changeX(t1);
- System.out.println("i2's value is "+t1.x);
- int j = t2.x;
- System.out.println("j's value is "+j);
- return j - i;
- }
- public static void changeX(Test9 t1) throws Exception{
- Class clazz = t1.getClass();
- Field fieldX = clazz.getDeclaredField("x");
- fieldX.setAccessible(true);
- fieldX.setInt(t1, 300);
- System.out.println("fieldX's vlaue is "+fieldX.getInt(t1));
- }
- public int test() throws Exception{
- return Method(this,this);
- }
- public static void main(String[] args) throws Exception{
- Test9 t1 = new Test9();
- System.out.println(t1.test());
- }
- }
复制代码 结果是
i's value is 100
fieldX's vlaue is 300
i2's value is 300
j's value is 300
200
为什么两种情况不一样?
|