java - 以通用方式获取 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() 函数做些什么改变,以便它与上面的泛型类一起工作。
解决方案
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.
推荐阅读
- javascript - pixi.js 性能不佳的着色器,并且 webgl 上下文丢失
- sql - SQL 中另一列中所有不同值的列中值的总和
- autodesk-forge - 仅在查询属性数据库后加载属性数据库或取消模型加载
- node.js - 如何在 apollo 订阅服务器上获取客户端 IP 地址?
- javascript - 如何合并对象数组和另一个对象数组
- eclipse - 如何修复Tomcat问题不适用于Eclipse?
- android - Android SQLite:这是否可以在查询的选择字段中放置 2 个参数?
- pycharm - 如何运行python脚本
- python - Gensim word2vec 下采样样本=0
- swift - 如何在 RealityKit 中旋转实体而不复制它?