gpt4 book ai didi

java - 获取Java类/对象的私有(private)属性列表

转载 作者:行者123 更新时间:2023-11-30 04:57:25 24 4
gpt4 key购买 nike

如何获取 getter 和 setter 中使用的 Java 对象的所有私有(private)属性的列表。我尝试了 PropertyUtilsMethodUtils 但没有运气。现在我尝试使用 Class 对象的 getDeclaredFields() ,该对象返回 Field 对象的列表,然后检查它是否是私有(private)属性,这是一种方法吗?或者有没有更好的解决方案。

最佳答案

这是一个相当老的问题帖子,但为了新的搜索,我将在这里提供答案。

使用@highlycaffeminate提供的方法:https://stackoverflow.com/a/6796254/776860

只需进行一些更改,您就可以轻松提出所需的解决方案。

仅检索私有(private)字段名称列表

public List<String> getMap(Object o) throws IllegalArgumentException, IllegalAccessException {
List<String> result = new ArrayList<String>();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if(!field.isAccessible()) {
result.add(field.getName());
}
}
return result;
}

检索所有字段名称及其值的映射

public Map<String, Object> getMap(Object o) throws IllegalArgumentException, IllegalAccessException {
Map<String, Object> result = new HashMap<String, Object>();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
result.put(field.getName(), field.get(o));
}
}
return result;
}

与 @highlycaffeina 完全相同,仅提供附加行 field.setAccessible(true);,它也使您能够内省(introspection) private 字段。

关于java - 获取Java类/对象的私有(private)属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com