• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to access object inside static block

 
Smilemaggy Rajendran
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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=(Class) hmap.get(key); // it works when i place the hashmap intialization inside main method but not working when i place Hashmap initialiastion in static block

return null;


}
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Move the declaration outside of the static initializer and just keep the put() calls inside.


 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the Map shouldn't change after it's initialized, you can add some safety to ensure it doesn't change:
Since there is no reference to the actual HashMap, the only way to access its contents is through the unmodifiable (i.e. read-only) map field. It's also made final to prevent it from being overwritten completely.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's also this atrocity, which uses an anonymous subclass of HashMap and that class's instance initalizer. Yuck.
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's just evil.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic