Java Reflection Snippet output -
i exploring java reflection api , encountered following code snippet
public class main { public static void main(string[] args) throws illegalaccessexception, nosuchfieldexception{ field value=integer.class.getdeclaredfield("value"); value.setaccessible(true); value.set(42, 43); system.out.printf("six times 7 %d%n",6*7); system.out.printf("six times 7 %d%n",42); system.out.println(42); } }
output :
six times 7 43 6 times 7 43 42
i read documentation of set method states sets value of field given object. not able understand output of code because should print 42 in cases.
can please give insight happening in code ?
system.out.println(42);
is calling println(int)
not println(object)
. boxing never happens. makes faster, , worked prior 1.5.
in other cases, boxing through integer.valueof(int)
. method defined returning same integer
objects values between -128 , 127 inclusive (may or may not have same behaviour other values). wherever 42 boxed in program same object, , when set value of value
in object changes no matter reference read through.
if put in boxing explicitly code, this:
value.set(integer.valueof(42), 43); system.out.printf("six times 7 %d%n",integer.valueof(6*7)); system.out.printf("six times 7 %d%n",integer.valueof(42)); system.out.println(42);
as know integer.valueof(
returns same object 42, code effectively:
integer obj42 = integer.valueof(42); value.set(integer.valueof(obj42, 43); system.out.printf("six times 7 %d%n", obj42); system.out.printf("six times 7 %d%n", obj42); system.out.println(42);
Comments
Post a Comment