Java反射获取所有私有字段 [英] Java reflection get all private fields
本文介绍了Java反射获取所有私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有办法获取java中某些类的所有私有字段及其类型。
I wonder is there a way to get all private fields of some class in java and their type.
例如假设我有一个类
class SomeClass {
private String aaa;
private SomeOtherClass bbb;
private double ccc;
}
现在我想得到所有私人字段(类
(不事先知道所有字段的名称)并检查它们的类型。 SomeClass的aaa
, bbb
, ccc
)
Now I would like to get all private fields (aaa
, bbb
, ccc
) of class SomeClass
(Without knowing name of all fields upfront) and check their type.
推荐答案
有可能获得所有使用方法 getDeclaredFields()
Class
的字段。然后你必须检查每个字段的修饰符以找到私有字段:
It is possible to obtain all fields with the method getDeclaredFields()
of Class
. Then you have to check the modifier of each fields to find the private ones:
List<Field> privateFields = new ArrayList<>();
Field[] allFields = SomeClass.class.getDeclaredFields();
for (Field field : allFields) {
if (Modifier.isPrivate(field.getModifiers())) {
privateFields.add(field);
}
}
请注意 getDeclaredFields()
不会返回继承的字段。
Note that getDeclaredFields()
will not return inherited fields.
最后,您将获得方法 Field.getType()。
这篇关于Java反射获取所有私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文