fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.lang.reflect.*;
  5.  
  6. /* Name of the class has to be "Main" only if the class is public. */
  7. class Ideone
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. doTricky1();
  12. doTricky2();
  13. System.out.printf(" 128 + 1 = %d\n",128+1);
  14. }
  15.  
  16. private static void doTricky1(){
  17. try{
  18. Class iCache=Integer.class.getDeclaredClasses()[0];
  19. Field f = iCache.getDeclaredField("cache");
  20. int low=-128;// low 保持不動
  21. int high=1000;//把 cache 從 -128~127 改為 -128~1000
  22.  
  23. Integer[] cacheArray=new Integer[high-low];
  24. for(int k = 0 , j=low ; k < cacheArray.length; k++)
  25. cacheArray[k] = new Integer(j++);
  26. setFinalStaticValue(f,cacheArray);
  27.  
  28. f = iCache.getDeclaredField("high");
  29. setFinalStaticValue(f,high);
  30.  
  31. }catch(Exception e){
  32. e.printStackTrace();
  33. }
  34. }
  35.  
  36. private static void doTricky2(){
  37. try{
  38. Class iCache=Integer.class.getDeclaredClasses()[0];
  39. Field f = iCache.getDeclaredField("cache");
  40. f.setAccessible(true);
  41. Integer[] cacheArray=(Integer[])f.get(iCache);
  42. cacheArray[257]=5; // 128 + 129 = 257
  43.  
  44. }catch(Exception e){
  45. e.printStackTrace();
  46. }
  47. }
  48.  
  49. private static void setFinalStaticValue(Field fd,Object val){
  50. try{
  51. fd.setAccessible(true);
  52. Field mdfField = Field.class.getDeclaredField("modifiers");
  53. mdfField.setAccessible(true);
  54. //重點是這裡,把 final 屬性拿掉
  55. mdfField.setInt(fd, fd.getModifiers() & ~Modifier.FINAL);
  56. fd.set(null, val);
  57. }catch(Exception e){
  58. e.printStackTrace();
  59. }
  60. }
  61. }
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
 128 + 1 = 5