Advertisement
DulcetAirman

Change String

Aug 27th, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.58 KB | None | 0 0
  1. package com.example.foo;
  2.  
  3. import java.lang.reflect.Field;
  4.  
  5. public class SomeClass {
  6.   public static void main(final String[] args) throws Throwable {
  7.     final String s = "Umesh";
  8.     changeString(s);
  9.   }
  10.  
  11.   // We need a method so the compiler won't inline "s":
  12.   static void changeString(final String s) throws Throwable {
  13.  
  14.     System.out.println("Original: " + s);
  15.     final Field field = String.class.getDeclaredField("value");
  16.     field.setAccessible(true);
  17.     final char[] value = (char[]) field.get(s);
  18.     value[0] = 'X';
  19.     System.out.println("Changed: " + s);
  20.   }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement