• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

how to access object inside static block

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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;


}
 
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Move the declaration outside of the static initializer and just keep the put() calls inside.


 
Sheriff
Posts: 22850
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 22850
132
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's just evil.
 
reply
    Bookmark Topic Watch Topic
  • New Topic