有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

类中的java静态字段

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

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

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

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

我需要一个例子来说明如何去做,或者其他什么方法能解决我的问题

谢谢


共 (4) 个答案

  1. # 1 楼答案

    您可以尝试使用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);
    
  2. # 2 楼答案

    作为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);
        }
    }
    
  3. # 3 楼答案

    static {}不是“静态名称空间”,它是一个静态初始值设定项块,用于初始化静态变量

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

    例如:

    public static List<Integer> colors = new ArrayList<>;
    
    static {
        colors.add (RED_050);
        ...
    }
    
  4. # 4 楼答案

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

    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方法。无需循环并添加到arrayList中

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

    更新:根据VBR建议,首选枚举集而不是列表

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