Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get HashMap with Reflection

public class First {
    public final static Map<String, String> MAP = new HashMap<>();
    static {
        MAP.put("A", "1");
        MAP.put("B", "2");
    }
}

public class Second {
    public static void main(String[] args) {
        Class<?> clazz = Class.forName("First");
        Field field = clazz.getField("MAP");
        Map<String, String> newMap = (HashMap<String, String>) field.get(null); // Obviously doesn't work
    }
}

Pretty much it. I have no trouble getting for example values of String variables, but I'm stuck with this one. Tryed to google it, failed. Also, if possible I'd like to get this Map without instantiating its class.

like image 696
Rinkashikachi Avatar asked Jun 27 '26 16:06

Rinkashikachi


1 Answers

The only thing you are missing is to handle the exceptions for:

  • Class.forName("First");
  • clazz.getField("MAP");
  • field.get(null);

The code below get the static map field from First class. Here I'm just throwing/propagating the exceptions in the main method but you should handle the exceptions in a try/catch block accordingly.

class First {
  public final static Map<String, String> MAP = new HashMap<>();
  static {
    MAP.put("A", "1");
    MAP.put("B", "2");
  }
}


public class Second {
  public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException,
      ClassNotFoundException, NoSuchFieldException, SecurityException {
    Class<?> clazz = Class.forName("First");
    Field field = clazz.getField("MAP");
    Map<String, String> newMap = (HashMap<String, String>) field.get(null); // Obviously doesn't work
    System.out.println(newMap); //Prints {A=1, B=2}
  }
}
like image 87
ChuyAMS Avatar answered Jun 30 '26 05:06

ChuyAMS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!