很多架構師都做錯的一道Integer的java基礎題
阿新 • • 發佈:2018-11-21
Integer a =1 , b= 2; System.out.println("before:a="+a+" b="+b); Field field = Integer.class.getDeclaredField("value"); field.setAccessible(true); int temp = a.intValue(); System.out.println("before:temp="+temp); field.set(a,b.intValue()); System.out.println("after:temp="+temp); field.set(b,temp); System.out.println("after:a="+a+" b="+b); Integer c= Integer.valueOf(1); Integer d= Integer.valueOf(2); Integer e= new Integer(1); System.out.println("before:c="+c+" d="+d +" e="+e);
題目很簡單,你做對了嗎?
Integer a =1 , b= 2; System.out.println("before:a="+a+" b="+b); Field field = Integer.class.getDeclaredField("value"); field.setAccessible(true); int temp = a.intValue(); System.out.println("before:temp="+temp); field.set(a,b.intValue()); System.out.println("after:temp="+temp); //set()的引數是Object,Object,而Object是引用型別,不是基本型別!所以這裡傳入的int temp=1,還需要先自動包裝成Integer,即Integer.valueOf(temp) //最後,利用反射給int value這個欄位設值的時候,其實使用到的是Integer.intValue()值 field.set(b,Integer.valueOf(temp).intValue()); field.set(b,temp); System.out.println("after:a="+a+" b="+b); Integer c= Integer.valueOf(1); Integer d= Integer.valueOf(2); Integer e= new Integer(1); System.out.println("before:c="+c+" d="+d +" e="+e);
before:a=1 b=2
before:temp=1
after:temp=1
after:a=2 b=2
before:c=2 d=2 e=1
Process finished with exit code 0