Created
September 28, 2017 15:37
-
-
Save simonesestito/d938e23eb7a062acb4ed3393c42b9e53 to your computer and use it in GitHub Desktop.
Change String value using reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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