how to access object inside static block

試著忘記壹切 提交于 2019-12-11 04:35:52

问题


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;
  }
}

回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/10018565/how-to-access-object-inside-static-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!