如何访问静态块内的对象 [英] how to access object inside static block

查看:90
本文介绍了如何访问静态块内的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静块内

我intialized哈希图,我需要访问HashMap对象使用我 getExpo 方法内键它来获得的值。



我的课程在这里

  public class ExampleFactory {
static
{
HashMap< String,Class<>> hmap = new HashMap< String,Class<>>();

hmap.put(app,application.class);
hmap.put(expo,expession.class);

$ b $ public void getExpo(String key,String expression)
{
//我需要访问静态块中的对象

class aclass = hmap.get(key); //当它放在main方法中时它工作,但
//不工作时,我将
的创建对象放在//静态块中的Hashmap

return null;


$ / code $ / pre

解决方案

Declare该变量作为类的静态成员,然后将其填充到静态块中:

  public class ExampleFactory 
{
// declare hmap
static HashMap< String,Class<>> hmap = new HashMap< String,Class<>>();
static
{
//填充hmap
hmap.put(app,application.class);
hmap.put(expo,expession.class);

$ b // ...
}

在此之后,您可以从您的课程内部访问它。



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


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

解决方案

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.

这篇关于如何访问静态块内的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆