-2

Have a look at this code:

 private static Map< String, Method > supplierFunctionMap = new HashMap< String, Method >();
    static
    {
        try {
            //ARP
            supplierFunctionMap.put( "206175-200", SupplierConfiguration.class.getDeclaredMethod("asd", String.class));
            supplierFunctionMap.put( "206175-210", SupplierConfiguration.class.getDeclaredMethod("asd", String.class));
            supplierFunctionMap.put( "206175-998", SupplierConfiguration.class.getDeclaredMethod("asd", String.class));
            //ADD new suppliers below
        } catch (NoSuchMethodException e) {
            System.out.println("Error in Key / Value of Hashmap. Maybe Key or Value not existing or something else is wrong.");
            e.printStackTrace();
        }
    }

The code under static{ is somehow connected with the hashmap. Because If I call this:

supplierFunctionMap.get("206175-200").invoke(null, supplierNumberAndAdmnr); 

Then the getDeclared method is called.

Can somebody explain why static{ like this can be declared and how it gets connected with the hashmap?

Ishaan Javali
  • 1,711
  • 3
  • 13
  • 23
Nuri Ensing
  • 1,899
  • 1
  • 19
  • 42
  • Reflection is slow, hard to debug, and cannot be optimized by the JIT compiler. You would be better off with a `Map>`. – VGR Dec 14 '18 at 15:16

1 Answers1

2

Well, your supplierFunctionMap is static. The static block is just adding items to the HashMap. static variables and any static blocks are initialised and executed upon class loading.

The static block is not connected to the HashMap, just your code indentation is wrong. You could put the static block further down.

The only connection is that the static block is adding items to the same HashMap.

jbx
  • 21,365
  • 18
  • 90
  • 144