通过反射获取Java中类的公共静态最终字段/属性的值
假设我有一堂课:
public class R {
public static final int _1st = 0x334455;
}
如何通过反射获取 "_1st" 的值?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
假设我有一堂课:
public class R {
public static final int _1st = 0x334455;
}
如何通过反射获取 "_1st" 的值?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(4)
首先检索类的字段属性,然后您可以检索值。如果您知道类型,则可以使用带有 null 的 get 方法之一(仅适用于静态字段,事实上,对于静态字段,传递给 get 方法的参数将被完全忽略)。否则,您可以使用 getType 并编写适当的开关,如下所示:
First retrieve the field property of the class, then you can retrieve the value. If you know the type you can use one of the get methods with null (for static fields only, in fact with a static field the argument passed to the get method is ignored entirely). Otherwise you can use getType and write an appropriate switch as below:
异常处理留给读者作为练习。
基本上,您可以通过反射像其他任何字段一样获取该字段,但是当您调用 get 方法时,您会传入 null,因为没有可操作的实例。
这适用于所有静态字段,无论它们是最终字段。如果该字段不是公共的,您需要先对其调用
setAccessible(true)
,当然 SecurityManager 必须允许所有这些。Exception handling is left as an exercise for the reader.
Basically you get the field like any other via reflection, but when you call the get method you pass in a null since there is no instance to act on.
This works for all static fields, regardless of their being final. If the field is not public, you need to call
setAccessible(true)
on it first, and of course the SecurityManager has to allow all of this.我正在寻找如何获得私有静态字段并登陆这里。
对于其他搜索者,方法如下:
I was looking for how to get a private static field and landed here.
For fellow searchers, here is how:
我遵循相同的路线(查看生成的 R 类),然后我有一种可怕的感觉,它可能是 Resources 类中的一个函数。我是对的。
发现这个:
Resources::getIdentifier
认为这可能会节省人们一些时间。尽管他们在文档中表示不鼓励这样做,但这并不奇怪。
I was following the same route (looking through the generated R class) and then I had this awful feeling it was probably a function in the Resources class. I was right.
Found this:
Resources::getIdentifier
Thought it might save people some time. Although they say its discouraged in the docs, which is not too surprising.