2012-04-04 54 views
1

我已经初始化静态块内的哈希映射,我需要访问哈希映射对象来获取值,使用它在我的getExpo方法中的键。如何访问静态块内的对象

我的类放在这里

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

声明变量作为类的静态成员,然后填充它在静态块:

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

    } 
    //... 
} 

在此之后,你可以从你的类里访问它。

在静态块中删除变量使其无法从该块外部访问。将它声明为类的成员使其可以被类访问。

+0

谢谢,我明白了 – Jessie 2012-04-04 23:15:00

1

你需要做hmap变量类的静态成员。

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

} 

因为它是正确的,现在你在静态块中声明它,所以一旦静态块执行,它就会丢失。

请注意,您需要确保访问hmap已同步或以其他方式线程安全,因为多个实例可能会同时修改地图。如果有意义的话,你可能还想要最终制作hmap