首页 > 解决方案 > 以通用方式获取 POJO 的属性

问题描述

我将对象的属性作为 List 获取,其中 AvsAttribute 如下:

     class AvsAttribute {
        String attrName,
        String value
    }

我正在为任何实体获取属性值,如下所示,因为我不想使用反射,这就是为什么这样做:

 @Override
  public List<AvsAttribute> getAttributes(List<String> attributeNameList, final @NonNull T entity)
  throws JsonProcessingException, JSONException {
  List<AvsAttribute> attributeList = new ArrayList<>();
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  String jsonString = objectMapper.writeValueAsString(entity);
  JSONObject jsonObject = new JSONObject(jsonString);
  Iterator<String> keysItr = jsonObject.keys();
  while (keysItr.hasNext()) {
    String key = keysItr.next();
    String value = jsonObject.get(key).toString().trim();
  attributeList.add(AvsAttribute.builder().name(key).value(value).build());
   }
  if (CollectionUtils.isNotEmpty(attributeNameList)) {
    return attributeList.stream().filter(item -> attributeNameList.contains(item.getName()))
      .collect(Collectors.toList());
}
return attributeList;

}

但我想让 AvsAttribute 像下面这样通用:

      class AvsAttribute<T> {
        String attrName,
        T value
    }

但我无法弄清楚我应该对上面的 getAttributes() 函数做些什么改变,以便它与上面的泛型类一起工作。

标签: javajava-8

解决方案


I think it already works with a generic type parameter. You need to setup the .value(String value) function in AvsAttribute builder to safely parse a given string into type T.
Then, you can rest assured that the following line will correctly fetch the generic attribute value:

AvsAttribute.builder().name(key).value(value).build()

Does that make sense?
Anyway, Good luck with your code.


推荐阅读