关于Java:如何循环访问存储在类中的一些系统常量

how to loop through some system constants stored in a class

我有一个带有一些系统常量的类,其中一些常量用于示例图像类型{jpg, png,jpeg}

在另一个类中,我正在检查提供的扩展名是否是systemConstants类中受支持的扩展名之一。

我想通过循环进行这种检查,但我不想手动进行一个接一个的检查。

为了进一步说明,如果用户输入了任何扩展名,我想检查它是否是有效扩展名,如下所示:

1
2
3
4
 if (ext != sysConstants.jpg || ext != sysConstants.jpeg || ext !=
    sysConstants.png) {
   //do smthing
 }

如何遍历这些常数?

更新:

eclipse用红色突出显示枚举,并表示无法解析为某种类型

1
2
3
4
5
6
7
8
public class EnumTest {

    public enum Ext {
        jpg,
        jpeg,
        png
    }
}


尽管您可以将常量存储在List中或为该常量声明一个枚举,但是您可以使用反射来遍历类中的字段。

假设您的常量在类中声明为public static final,则可以执行

1
2
3
4
5
    for (Field f : YourClass.class.getDeclaredFields()) {
        f.setAccessible(true); // you need this if variables are private
        String name = f.getName();
        String value = (String) f.get(null);
    }

遍历所有领域。

please also tell me why do u use null

我假设您的常数是静态的。 如果不是,则应在参数中使用实际的实例/对象。 对于静态成员,可以使用null。 根据Java文档

1
If the underlying field is a static field, the obj argument is ignored; it may be null.


用户枚举来澄清您的代码:

1
2
3
public enum ImageTypes {
    JPG, PNG, TIFF
}

然后您得到一个图像类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ImageType type = ext;

switch(ext) {
    case JPG:
      // do your stuff...
    break;


    // other cases

    default:
        // error;
    break;

}