Rae*_*loz 1 java static initialization
我试图理解ZXing的CharacterSetECI.java在其静态初始化器中正在做什么
具体来说,我不知道这是怎么回事:
private static final Map<Integer,CharacterSetECI> VALUE_TO_ECI = new HashMap<>();
private static final Map<String,CharacterSetECI> NAME_TO_ECI = new HashMap<>();
static {
for (CharacterSetECI eci : values()) {
for (int value : eci.values) {
VALUE_TO_ECI.put(value, eci);
}
NAME_TO_ECI.put(eci.name(), eci);
for (String name : eci.otherEncodingNames) {
NAME_TO_ECI.put(name, eci);
}
}
}
private final int[] values;
Run Code Online (Sandbox Code Playgroud)
注意在第一个foreach中使用values(),方法values()没有在类中的任何地方定义.最接近它的是它下面定义的int数组值,但我认为我们可以同意它肯定不包含CharacterSetECI类型对象.
当我尝试在新类中仅键入这段代码(创建构造函数,最终实例变量数组和静态初始化程序)时,Eclipse会抱怨values()未定义,但是当我将整个代码复制到新类时, Eclipse只是抱怨几种类型无法解析,但是values()得到了一个传递.我试图按住Ctrl键并单击值()来查看它引用的内容,但它不可点击.
注意:
如果您不信任链接,则此类可在ZXing的3.1.0版源代码中获得,可在mavencentral中的com.google.zxing.common包中找到.
每个enum都有一个隐含的values方法; 来自JLS§8.9.3:
枚举类型的成员
E都是以下所有成员:
...
以下隐式声明的方法:
Run Code Online (Sandbox Code Playgroud)/** * Returns an array containing the constants of this enum * type, in the order they're declared. This method may be * used to iterate over the constants as follows: * * for(E c : E.values()) * System.out.println(c); * * @return an array containing the constants of this enum * type, in the order they're declared */ public static E[] values();