how to access object inside static block

Go To StackoverFlow.com

1

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;
  }
}
2012-04-04 20:13
by Jessie


1

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.

2012-04-04 20:18
by Attila
Thank you, I got it wor - Jessie 2012-04-04 23:15


1

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.

2012-04-04 20:16
by hvgotcodes
Ads