Java:如何使用类属性创建映射?

Java:如何使用类属性创建映射?,java,Java,我正在尝试从类具有的所有属性创建映射。我的类如下所示: public class MyInventory { private int tiers = 80; private int stearing =135; private int battery = 46; } 现在我收集了该类的所有方法,如下所示: Field[] fields = this.getClass().getDeclaredFields(); 现在,我正在尝试创建一个映射,其中键是字段的值,值是字段的

我正在尝试从类具有的所有属性创建映射。我的类如下所示:

public class MyInventory
{
   private int tiers = 80;
   private int stearing =135;
   private int battery = 46;

 }
现在我收集了该类的所有方法,如下所示:

Field[] fields = this.getClass().getDeclaredFields();
现在,我正在尝试创建一个映射,其中键是字段的值,值是字段的名称。例如:

Map<46,battery> ...etc
Map…等
有办法吗? 上述类的属性值是通过映射到属性文件并使用spring annotation@ConfigurationProperties生成的。现在我需要创建贴图,但为属性的值设置关键帧。我试着使用反射。但是,没有找到获取字段值的方法


谢谢

我想,你可以在课堂上使用getter方法

public class MyInventory
{
   private int tiers = 80;
   private int stearing =135;
   private int battery = 46;

   public int getBattery()
   {
       return battery;
   }
  //and other getter 
 }
然后,您可以将地图填充为

map.put(inventory.getBattery(),"battery");

因为,当您有值时,这意味着您知道要填充映射的类型。

您可以使用
Introspector

public Map<Object, String> populateMap(final Object o) throws Exception {
  Map<Object, String> result = new HashMap<>();
  for (PropertyDescriptor pd : Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors()) {
    String fieldName = pd.getName();
    if("class".equals(fieldName) continue;
    Object value = pd.getReadMethod().invoke(o);
    result.put(value, fieldName);
  }
  return result;
}
Map Map()抛出IllegalArgumentException,IllegalAccessException{
字段[]字段=getClass().getDeclaredFields();
Map Map=newhashmap();
用于(字段:字段){
map.put(field.getInt(this),field.getName());
}
返回图;
}

当然,如果不同的字段具有相同的值,它将无法正确映射

您可以使用json解析器。例如,杰克逊:

  import com.fasterxml.jackson.databind.ObjectMapper;
  ... 
  ObjectMapper mapper = new ObjectMapper();
  return mapper.readValue(mapper.writeValueAsString(fooOject), HashMap.class);

所以你想创建一个
映射图
-有什么问题吗?听起来很奇怪,我们通常按字段名创建键,反之亦然。无论如何,这是可能的。只需使用reflect api@BalwinderSingh
Map
*;)@这是真的。我想是匆忙打字;)如果你已经完成了你的课程,你为什么还需要一张地图呢?如果使用MyInventory的列表,不是会更简单吗?我得到:线程“main”java.lang.ClassCastException中的异常:java.lang.Class不能转换为java.lang.Integer
  Map<Integer, String> map() throws IllegalArgumentException, IllegalAccessException {

       Field[] fields = getClass().getDeclaredFields();
       Map<Integer,String> map = new HashMap<>();
       for (Field field : fields) {
           map.put(field.getInt(this), field.getName());
       }
       return map;
   }
  import com.fasterxml.jackson.databind.ObjectMapper;
  ... 
  ObjectMapper mapper = new ObjectMapper();
  return mapper.readValue(mapper.writeValueAsString(fooOject), HashMap.class);