Galera andei lendo uns tópicos sobre wrap, reflection e tals…Olhe o codigo abaixo:
Fieldf=Integer.class.getDeclaredField("value");f.setAccessible(true);Integertwo=2;f.set(two,3);System.out.printf("The value of two is now '%d' %n",two);Integerx;x=2;x=x+2;System.out.printf("The value of x is now '%d' %n",x);//5f.set(x,2);System.out.printf("The value of x is now '%d' %n",x);//3x=x+2;System.out.printf("The value of x is now '%d' %n",x);//3f.set(x,10);System.out.printf("The value of x is now '%d' %n",x);//10
A minha dúvida é porque neste trecho:
f.set(x,2);System.out.printf("The value of x is now '%d' %n",x);//3
Fieldf=Integer.class.getDeclaredField("value");f.setAccessible(true);Integertwo=2;f.set(two,3);System.out.printf("The value of two is now '%d' %n",two);Integerx;x=2;x=x+2;System.out.printf("The value of x is now '%d' %n",x);//5f.set(x,2);System.out.printf("The value of x is now '%d' %n",x);//3 Porque aqui é impresso 3 e não 2?x=x+2;System.out.printf("The value of x is now '%d' %n",x);//3f.set(x,10);System.out.printf("The value of x is now '%d' %n",x);//10
Stormqueen1990
Dá uma lida lá no tópico.
A explicação é que o 2, nesse ponto
Integer x;
x = 2;
não é um valor inteiro, mas sim um “ponteiro” para um objeto do tipo Integer que foi criado anteriormente e que teve valor 3 atribuído a ele.
T
thingol
O compilador transforma o seu código para o seguinte código equivalente:
Integertwo=Integer.valueOf(2);f.set(two,Integer.valueOf(3));System.out.printf("The value of two is now '%d' %n",two);Integerx;x=Integer.valueOf(2);x=Integer.valueOf(x.intValue()+2);System.out.printf("The value of x is now '%d' %n",x);//5 f.set(x,Integer.valueOf(2));System.out.printf("The value of x is now '%d' %n",x);//3 Porque aqui é impresso 3 e não 2? x=Integer.valueOf(x.intValue()+2);System.out.printf("The value of x is now '%d' %n",x);//3 f.set(x,Integer.valueOf(10));System.out.printf("The value of x is now '%d' %n",x);//10
Acompanhe passo a passo e veja o que ocorre. É aconselhável usar um debugger para ver com atenção o que ocorreu.
Stormqueen1990
thingol:
O compilador transforma o seu código para o seguinte código equivalente:
Integertwo=Integer.valueOf(2);f.set(two,Integer.valueOf(3));System.out.printf("The value of two is now '%d' %n",two);Integerx;x=Integer.valueOf(2);x=Integer.valueOf(x.intValue()+2);System.out.printf("The value of x is now '%d' %n",x);//5 f.set(x,Integer.valueOf(2));System.out.printf("The value of x is now '%d' %n",x);//3 Porque aqui é impresso 3 e não 2? x=Integer.valueOf(x.intValue()+2);System.out.printf("The value of x is now '%d' %n",x);//3 f.set(x,Integer.valueOf(10));System.out.printf("The value of x is now '%d' %n",x);//10
Acompanhe passo a passo e veja o que ocorre. É aconselhável usar um debugger para ver com atenção o que ocorreu.
Esse esquema aí é bem bom pra fazer uma bela porcaria sem se dar conta.
emmanuelrock
É bem complexo esse processo, vou gastar um tempão depurando até entender hehe…Obrigado pela atenção de todos!