使用反射检查java中字段是否为final的最佳方法是什么? [英] What is the best way to check if a field is final in java using reflection?

查看:216
本文介绍了使用反射检查java中字段是否为final的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个类,在某个时候,必须从该类的其他项目中分配所有字段。

I'm writing a class, which, at some point, has to have all its fields assigned from an other item of this class.

我通过它完成了反射:

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.

使用反射检查java中字段是否为final的最佳方法是什么?

What's the best way to check if a field is final in java using reflection?

推荐答案

最好也是唯一的一种方法是: Modifier.isFinal(f.getModifiers())

The best and only one way is: Modifier.isFinal(f.getModifiers())

参考:

  • Field.getModifiers
  • Modifier.isFinal

这篇关于使用反射检查java中字段是否为final的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆