This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes how to access object inside static block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to access object inside static block" Watch "how to access object inside static block" New topic
Author

how to access object inside static block

Smilemaggy Rajendran
Greenhorn

Joined: Apr 04, 2012
Posts: 4
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

Joined: Jan 03, 2004
Posts: 6109
    
    6

Move the declaration outside of the static initializer and just keep the put() calls inside.


Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

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

Joined: Jan 03, 2004
Posts: 6109
    
    6

There's also this atrocity, which uses an anonymous subclass of HashMap and that class's instance initalizer. Yuck.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19656
    
  18

That's just evil.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to access object inside static block
 
Similar Threads
dynamic (?!) casting
Maintaining the order in a collection.
static objects
Storing objects in hashmap
OOP-4 Lookup hashmap