[英]Iterate over Two Class with constants and load their fields into a HashMap
我有两个带有常量的Java类,例如:
public class FirstClass {
public static final String STRING_A = "STRING_A";
public static final String STRING_B = "STRING_B";
public static final String STRING_C = "STRING_C";
...
}
public class SecondClass {
public static final String STRING_AA = "STRING_AA";
public static final String STRING_BA = "STRING_BA";
public static final String STRING_CA = "STRING_CA";
...
}
现在,我想将这些常量加载到Map <String,String> classPropertyMap = new HashMap <>();中。 以这种方式,此映射的Key必须是FirstClass的常量,而对应的值必须是SecondClass的常量。
如果这只是一个类,那么由于常量来自两个类,我现在可以使用反射来加载字段,这怎么办?
最后,加载地图后,地图的内容必须类似于以下内容:
第一个元素:键和值是<STRING_A,STRING_AA>
第二个元素:键和值是<STRING_B,STRING_BA>
第三个元素:键和值是<STRING_C,STRING_CA>
我认为,如果您确实需要它,最可靠的方法是将属性明确地放入地图。
我的意思是map.put(FirstClass.STRING_A, SecondClass.STRING_AA);
等等。
如果使用反射,则依赖属性,并且它们的声明顺序永远不会改变。 如果在库中引入了一些新属性,则可能会破坏您的代码。
尝试以下类似的方法,看来可以实现。
FirstClass first = new FirstClass();
Field[] fields = first.getClass().getFields();
SecondClass second = new SecondClass();
Field[] fields1 = second.getClass().getFields();
尝试这个:
FirstClass first = new FirstClass();
String[] firstStrings = first.getStrings();
//Makes a String array, and fills it with the strings from the first class.
SecondClass second = new SecondClass();
String[] secondStrings = second.getStrings();
//Makes a String array, and fills it with the strings from the second class.
HashMap<String, String> classPropertyMap = new HashMap<String, String>();
int i = 0;
//Now put strings with the same index number from both arrays into the
//HashMap
while(i <= firstStrings.length()){
classPropertyMap.put(firstStrings.get(i), secondStrings.get(i);
i++;
}
希望能成功!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.