I have intialized Hash map inside static block, I need to access the hashmap object to get the value using key it inside my getExpo
method.
My class goes here
public class ExampleFactory {
static
{
HashMap<String,Class<?>> hmap = new HashMap<String,Class<?>>();
hmap.put("app", application.class);
hmap.put("expo", expession.class);
}
public void getExpo(String key,String expression)
{
// I need to access the object in static block
Class aclass=hmap.get(key); // it works when i place it inside main method but
// not working when i place the create object for
// Hashmap in static block
return null;
}
}
Declare the variable as a static member of the class, then populate it in the static block:
public class ExampleFactory
{
// declare hmap
static HashMap<String,Class<?>> hmap = new HashMap<String,Class<?>>();
static
{
// populate hmap
hmap.put("app", application.class);
hmap.put("expo", expession.class);
}
//...
}
After this you can access it from inside your class.
Delcaring the variable within the static block makes it unaccessible from outside that block. Declaring it as member of the class makes it accessible to the class.
You need to make the hmap
variable a static member of the class.
public class YourClass {
private static Map<String, Class<?>> hmap = new HashMap<String, Class<?>>();
static {
// what you did before, but use the static hmap
}
public void getExpo(...){
Class aClass = YourClass.hmap.get(key);
}
}
as it stands right, now you are declaring it in the static block, so it's lost once the static block executes.
Note you need to be sure access to hmap
is synchronized or otherwise thread-safe, since multiple instances might modify the map at the same time. If it makes sense, you might also want to make hmap
final.