fork download
  1. import java.lang.reflect.Field;
  2. import java.util.Arrays;
  3.  
  4. public class Main {
  5. public static void main(String[] args) throws Exception {
  6. // 1. 创建一个普通的 String
  7. String original = new String("hello");
  8. System.out.println("修改前: " + original);
  9.  
  10. // 2. 获取 String 类中名为 "value" 的私有字段(JDK 9+ 中它是 byte[])
  11. Field valueField = String.class.getDeclaredField("value");
  12. // 关键:突破 private 访问限制
  13. valueField.setAccessible(true);
  14.  
  15. // 3. 取出这个 String 实例内部的 byte[] 数组引用
  16. byte[] internalBytes = (byte[]) valueField.get(original);
  17.  
  18. // 4. 直接修改这个数组的第 0 个字节
  19. // 'h' 的 ASCII 码是 104,'H' 的 ASCII 码是 72
  20. internalBytes[0] = 72;
  21.  
  22. // 5. 见证“奇迹”
  23. System.out.println("修改后: " + original);
  24. System.out.println("内部字节数组: " + Arrays.toString(internalBytes));
  25. }
  26. }
Success #stdin #stdout #stderr 0.13s 19128KB
stdin
Standard input is empty
stdout
修改前: hello
修改后: Hello
内部字节数组: [72, 101, 108, 108, 111]
stderr
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by Main (file:/home/run-20079/tested.zip) to field java.lang.String.value
WARNING: Please consider reporting this to the maintainers of Main
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release