Skip to content

Instantly share code, notes, and snippets.

@simonesestito
Created September 28, 2017 15:37
Show Gist options
  • Save simonesestito/d938e23eb7a062acb4ed3393c42b9e53 to your computer and use it in GitHub Desktop.
Save simonesestito/d938e23eb7a062acb4ed3393c42b9e53 to your computer and use it in GitHub Desktop.
Change String value using reflection
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class Main
{
public static void main(String[] args) throws Exception {
//Create a new String "Hello"
String s = "Hello";
//Change the value of "s" variable to "Goodbye"
change(s, "Goodbye");
//Print it to see the change
System.out.println(s);
}
private static void change(String s, String val) throws Exception {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
Field mod = Field.class.getDeclaredField("modifiers");
mod.setAccessible(true);
mod.setInt(value, value.getModifiers() & ~Modifier.FINAL);
value.set(s, val.toCharArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment