我有一个Java常量文件,其中包含大约1000条记录,并且全部都是字符串类型 例如
public static String PF_EMPLOYER = "PF-Employer";
public static String ESI_EMPLOYER = "ESI-Employer";
public static String TOTAL_CTC = "Total CTC";
public static String INCENTIVE = "Incentive";
public static String PF_EMPLOYEE = "PF-Employee";
public static String ESI_EMPLOYEE = "ESI-Employee";
==and so on could be more than 1000=======
我只想静态 ArrayList 或 HashMap 中的所有字符串值,其中 HashMap 中的整数将为 0,1,2,3....1000。
我一直在寻找任何有效的方法来完成这项任务,即使 Spring 提供了任何解决方案,我也准备好接受它。
我无法在任何属性文件中移动常量文件内容。
请注意,我使用的是 JDK 7,不可能使用 JDK 8。
最佳答案
如果我正确理解您的要求,那么执行您想要的操作的唯一自然方式应该是使用反射。如果您的类名称是 ConstClass
它可能类似于:
HashMap<String, String> map = new HashMap<>();
for (Field field: ConstClass.class.getFields()) {
if (String.class.isAssignableFrom(field.getType())) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
map.put(field.getName(), (String) field.get(ConstClass.class));
}
}
}
您在映射
中获得包含静态字符串
的所有字段。
关于java - 如何创建包含所有java类常量的HashMap或Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087015/