我有一个类的实例,我想为其创建一个 Map,其中 Key 作为每个类变量名称,其 Value 作为该类变量中的值?
我尝试使用以下方法,但似乎不起作用。它不会进入 if() 或 else if() 部分。并且 map 仍然是空的。
有人能解决这里的问题吗?谢谢
public class ClassA {
private String optionOne = "1";
private Int optionTwo = 2;
}
Map<String, String> map = new HashMap<>();
Map<String, Integer> mapInt = new HashMap<>();
for (Field field : ClassA.class.getFields()) {
field.setAccessible(true);
if (field.getType().equals(String.class)){
map.put(field.getName(), (String) field.get(object));
} else if (field.getType().equals(Integer.class)) {
mapInt.put(field.getName(), (Integer) field.get(object));
}
}
最佳答案
将 getFields
更改为 getDeclaredFields
,将 Integer.class
更改为 int.class
,因为字段 optionTwo
是 int
而不是 Integer
。
Map<String, String> map = new HashMap<>();
Map<String, Integer> mapInt = new HashMap<>();
for (Field field : ClassA.class.getDeclaredFields()) {
field.setAccessible(true);
if (field.getType().equals(String.class)){
map.put(field.getName(), (String) field.get(object));
} else if (field.getType().equals(int.class)) {
mapInt.put(field.getName(), (Integer) field.get(object));
}
}
关于Java:将类成员变量/值转换为 Map - 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51414861/