Advertisement
Guest User

Why not change strings in java(w/ reflection)

a guest
Nov 3rd, 2014
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. //This is what happens if you change a string using reflection.(Only for interned(hardcoded) strings)
  2. import java.lang.reflect.Field;
  3.  
  4. public class MutateString {
  5.  
  6.     public static final String addr = "ADDR_PLACEH";
  7.    
  8.     //Results:
  9.     //Initial: ADDR_PLACEH
  10.     //From var: 192.168.1.1
  11.     //Hardcoded: 192.168.1.1
  12.     //Substring: ADDR_PLACEH
  13.     //Equals test: true
  14.     //Equals test with substring: false
  15.     public static void main(String[] args) {
  16.         System.out.print("Initial: "); System.out.println(addr);
  17.         editIntStr("ADDR_PLACEH", "192.168.1.1");
  18.         System.out.print("From var: "); System.out.println(addr);
  19.         System.out.print("Hardcoded: "); System.out.println("ADDR_PLACEH");
  20.         System.out.print("Substring: "); System.out.println("ADDR_PLACE" + "H".substring(0));
  21.         System.out.print("Equals test: "); System.out.println("ADDR_PLACEH".equals("192.168.1.1"));
  22.         System.out.print("Equals test with substring: ");  System.out.println(("ADDR_PLACE" + "H".substring(0)).equals("192.168.1.1"));
  23.     }
  24.  
  25.     public static void editIntStr(String from, String to) {
  26.         Field f = null;
  27.         try {
  28.             f = String.class.getDeclaredField("value");
  29.         } catch (NoSuchFieldException e) {
  30.             e.printStackTrace();
  31.         }
  32.         f.setAccessible(true);
  33.         try {
  34.             f.set(from, to.toCharArray());
  35.         } catch (IllegalAccessException e) {
  36.             e.printStackTrace();
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement