class 中的静态字段

Static fields in class

我有一个 class,它有数百个静态字段,int 字段表示颜色。

public class LColorPallette {
      public static final int RED_050 = 0xfde0dc;
      ...
}

我想将它们放在一个容器中,该容器可以是 arraylist、map 或 set。我知道可以声明一个静态名称空间,这样就会有类似的东西

public class ColorPalletteSingleton {
      static {
            container.add(...);
            ...
}

我需要一个例子来说明如何做或任何其他方法可以解决我的问题吗?

谢谢

static {}不是"static namespace",它是静态初始化块,用于初始化静态变量。

您可以将颜色存储在静态 Collection 中。

例如:

public static List<Integer> colors = new ArrayList<>;

static {
    colors.add (RED_050);
    ...
}

而不是静态字段更喜欢枚举。

What's the advantage of a Java enum versus a class with public static final fields?

 enum LColorPallette {
    RED_050(0xfde0dc);
    private int hexValue;

    private LColorPallette(int hexValue) {
        this.hexValue = hexValue;
    }

    public String getHexValue()
    {
        return Integer.toHexString(hexValue);
    }

}

Enum 有 values 方法 return array.No 需要循环并添加到 arrayList

 List<LColorPallette> somethingList = Arrays.asList(LColorPallette .values());

UPDATE :正如 VBR 推荐的那样,首选 EnumSet 而不是 List

EnumSet set = EnumSet.allOf(LColorPallette .class);

您可以尝试使用 reflection 获取所有字段。

    List<Integer> result = new ArrayList<Integer>();
    Field[] fields = LColorPallette.class.getDeclaredFields();
    for(Field classField : fields){
        result.add(classField.getInt(classField.getName()));    
    }
    System.out.println(result);

作为 Map:

public static final int RED_050 = 0xfde0dc;
public static final int RED_051 = 0xfde0df;

public void test() throws IllegalArgumentException, IllegalAccessException {
    Map<String, Integer> colours = new HashMap<>();
    Class<Test> myClass = (Class<Test>) this.getClass();
    Field[] fields = myClass.getDeclaredFields();
    for (Field field : fields) {
        Type type = field.getGenericType();
        // TODO: Make sure it is an int
        int value = field.getInt(field);
        System.out.println("Field " + field.getName() + " type:" + type + " value:" + Integer.toHexString(value));
        colours.put(field.getName(), value);
    }
}