java 使用反射检查Java中的字段是否为final
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7560285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a field is final in java using reflection
提问by Arsen Zahray
I'm writing a class, which at some point has to have all its Field
s assigned from another item of this class.
我正在编写一个类,它在某些时候必须Field
从该类的另一个项目中分配所有的s。
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
. I could skip it by name, but to me that seems not elegant at all.
问题是,这个类包含一个Field
,即final
。我可以按名字跳过它,但对我来说这似乎一点也不优雅。
What's the best way to check if a Field
is final
in java using reflection?
使用反射检查 aField
是否final
在 java 中的最佳方法是什么?
回答by AlexR
The best and only one way is: Modifier.isFinal(f.getModifiers())
最好也是唯一的一种方法是: Modifier.isFinal(f.getModifiers())
Reference:
参考:
回答by Aleks G
You can use getModifiers()
method on the Field
variable:
您可以getModifiers()
在Field
变量上使用方法:
if ((f.getModifiers() & Modifier.FINAL) == Modifier.FINAL)
{
//this is final field
}