简体   繁体   English

使用反射检查java中的字段是否为final

[英]Check if a field is final in java using reflection

I'm writing a class, which at some point has to have all its Field s assigned from another item of this class. 我正在写一个类,它在某些时候必须从该类的另一个项目中分配所有的Field

I did it through reflection: 我通过反思做到了:

for (Field f:pg.getClass().getDeclaredFields()) {
    f.set(this, f.get(pg));
}

The problem is, that this class contains a Field , which is final . 问题是,这个类包含一个Field ,这是final I could skip it by name, but to me that seems not elegant at all. 我可以跳过它的名字,但对我来说似乎并不优雅。

What's the best way to check if a Field is final in java using reflection? 使用反射检查一个Field是否是final的最佳方法是什么?

The best and only one way is: Modifier.isFinal(f.getModifiers()) 最好也是唯一的一种方法是: Modifier.isFinal(f.getModifiers())

Reference: 参考:

You can use getModifiers() method on the Field variable: 您可以在Field变量上使用getModifiers()方法:

if ((f.getModifiers() & Modifier.FINAL) == Modifier.FINAL)
{
    //this is final field
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM