java 反射私有字段,Java反射获取所有私有字段

在Java中,可以使用`getDeclaredFields()`方法获取类的所有字段,然后通过检查每个字段的修饰符来过滤出私有字段。此方法不会包含继承的字段。接着,利用`Field.getType()`获取字段的类型。
摘要由CSDN通过智能技术生成

I wonder is there a way to get all private fields of some class in java and their type.

For example lets suppose I have a class

class SomeClass {

private String aaa;

private SomeOtherClass bbb;

private double 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.

解决方案

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 privateFields = new ArrayList<>();

Field[] allFields = SomeClass.class.getDeclaredFields();

for (Field field : allFields) {

if (Modifier.isPrivate(field.getModifiers())) {

privateFields.add(field);

}

}

Note that getDeclaredFields() will not return inherited fields.

Eventually, you get the type of the fields with the method Field.getType().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值