【问题标题】:Java : How to create map using the class attributes?Java:如何使用类属性创建地图?
【发布时间】:2018-10-12 03:26:40
【问题描述】:

我正在尝试从一个类的所有属性创建一个映射。我的类看起来像:

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

 }

现在我已经收集了该类的所有方法:

Field[] fields = this.getClass().getDeclaredFields();

现在,我正在尝试从中创建一个 Map,其中键是字段的值,值是字段的名称。示例:

Map<46,battery> ...etc

有办法吗? 上述类的属性值是通过映射到属性文件并使用spring注解@ConfigurationProperties生成的。现在我需要创建 Map 但键属性的值。我尝试使用反射。但是没有找到获取字段值的方法。

谢谢

【问题讨论】:

  • 所以你想创建一个Map&lt;int,String&gt; - 有什么问题?
  • 听起来很奇怪,我们经常按字段名创建键,反之亦然。无论如何,这是可能的。只需使用反射 api docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html
  • @BalwinderSingh Map&lt;Integer, String&gt; * ;)
  • @Eng.Fouad 是真的。我想是匆忙输入的;)
  • 如果你已经完成了你的课程,为什么还需要一张地图?如果使用 MyInventory 列表会不会更简单?

标签: java


【解决方案1】:

你可以使用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;
}

您可以调用上述方法,将您的类作为参数传递。

MyInventory mi = new MyInventory();
// Sets the properties of mi
mi.setXXX...
// Populates map
populateMap(mi);

【讨论】:

  • 我得到:线程“main”中的异常 java.lang.ClassCastException:java.lang.Class 无法转换为 java.lang.Integer
【解决方案2】:
  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;
   }

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

【讨论】:

    【解决方案3】:

    我认为,你可以在课堂上使用 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");
    

    因为,当您拥有价值时,这意味着您知道要为其填充地图的类型是什么。

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-20
        相关资源
        最近更新 更多