问题与Android的静态code [英] Issue with static code in Android

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

问题描述

我建立我自己的类,它类似于一个枚举。这里的code:

I am building my own class, which is similar to an Enum. Here's the code:

public final class MyClass {
    public final static MyClass V1 = new MyClass("v1");
    public final static MyClass V2 = new MyClass("v2");
    public final static MyClass V3 = new MyClass("v3");

    private static Map<String, MyClass> values;
    private final String name;

    private MyClass(String name) {
        this.name = name;
        if (values == null)
            values = new HashMap<>();
        values.put(name,this);
    }

    public static MyClass[] values() {
        return values.values().toArray(new MyClass[values.size()]);
    }

    public static MyClass valueOf(String key) {        
        return values.get(key);    
    }

    public String getName() {        
        return name;    
    }

    public String toString() { 
        return getName(); 
    }

    public static void print() {
        Iterator<Map.Entry<String, MyClass>> i = values.entrySet().iterator();
        while (i.hasNext()) {
            String key = i.next().getKey();
            System.out.println(MyClass.class.getSimpleName() + ": " + key + ", " + values.get(key));
        }
    }
}

我观察怪异的行为:当我尝试调用 MyClass.valueOf(V1)我得到
我试着调试和:

I am observing a weird behavior: when I try to invoke MyClass.valueOf("v1") I get null. I tried to debug and:


  • 构造函数中长的valueOf 被调用(当调用打印,它被调用3次)
  • 援引前
  • 被填充(最后一个构造函数调用,当然,作为地图的大小为3,符合市场预期。

  • 的valueOf 为空

  • the constructor is invoked long before valueOf is invoked (when I invoke print, it gets invoked 3 times)
  • values gets populated (last constructor invocation, of course, takes the map size to 3, as expected.
  • when in valueOf, values is empty

====更新

只有当我在调试模式下,把一个断点在打印方法,那么我可以看到打印到控制台上的枚举类级的价值观。当我做htis,的valueOf 返回正确的结果。

ONLY if I am in debug mode and put a breakpoint in the print method, then I can see the "enum-like-class" values printed in the console. When I do htis, valueOf returns the correct results.

这是怎么回事?

推荐答案

目前,我找到解决这个问题的最佳途径是其他静态变量之前搬走价值的定义和初始化。
这样,被调用构造函数之前被初始化。

Currently, the best way I found to tackle the issue is to move values definition and initialization before the other static variables. This way, it gets initialized before the constructors are invoked.

看看这个:<一href=\"http://stackoverflow.com/questions/35297662/static-initializer-not-called-on-activity-creation/35297732#35297732\">Static初始化不叫上的活动创造

这篇关于问题与Android的静态code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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