在Java中强制初始化枚举类型 [英] Force Initialization of an enumerated type in Java

查看:168
本文介绍了在Java中强制初始化枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来强制Java加载/初始化枚举类型(嵌套在包含静态Map的类中)。

I am attempting to find a way to force Java to load/initialize an enumerated type (which is nested within a class that contains a static Map).

这对我来说很重要,因为枚举类型有一个构造函数来填充所述地图,并且没有明确的方法来初始化这个枚举,地图将保持为空。我试图使用 Class.forName ,但这似乎不起作用。

This is important to me because the enumerated type has a constructor that populates said map, and without an explicit way to initialize this enum, the map will remain empty. I have attempted to use Class.forName, but this does not seem to work.

我想我可以创建枚举的一个实例(并将其存储在soem其他集合或其他东西中),但我想知道是否有一种优雅的方法来执行此操作。

I suppose I could create an instance of the enum (and store it in soem other collection or something), but I would like to know if there is an elegant way to do this.

推荐答案

引用类时会加载一个类。这适用于所有类。

A class is loaded when you reference a class. This works the same for all classes.

您遇到的问题更可能是在任何静态块之前初始化Enum值。即你不能引用构造函数中静态块中的初始化。 (通常在构造函数中初始化静态内容是一个坏主意)您需要在静态块中初始化Map,而不是构造函数。

The problem you have is more likely to be that an Enum value is initialised before any static block. i.e. you cannot refer to something initialise in a static block in a constructor. (Generally initialising static content in a constructor is a BAD idea) You need to initialise the Map in the static block, not the constructor.

尝试

import java.util.Map; 
import java.util.HashMap; 

public enum EnumTest { 
  FOO, BAR, BAZ; 

  private static final Map<String,EnumTest> map = new LinkedHashMap<String,EnumTest>(); 
  static { 
      for(EnumTest e : EnumTest.values())
        map.put(e.name(), e); 
  } 

  public static void main(String... args) { 
    System.out.println(EnumTest.map); 
  } 
}

这篇关于在Java中强制初始化枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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