反射:通过反射加载类中的常量变量
我有一个类,其中有一堆常量字符串。
我需要通过反射加载此类并检索这些常量。 我可以达到:
controllerClass = Class.forName(constantsClassName);
Object someclass = controllerClass.newInstance();
但我对如何检索此类中的字段感到困惑。
I have a class which has a bunch of Constant Strings.
I need to load this class via reflection and retrieve those constants.
I can get up to:
controllerClass = Class.forName(constantsClassName);
Object someclass = controllerClass.newInstance();
but I am confused on how to retrieve the fields in this class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
访问字段的快速示例 --
A quick sample on accessing fields --
下面是一个小示例:
运行这个小程序输出:
一些观察结果:
对于静态字段,为
Field.get()
提供的对象可以为null
。 p>为了简洁起见,我在
Exception
基类中使用了异常捕获 - 您应该在代码中使用显式异常类。虽然
Field.get()
通常按预期工作,但Field.set()
及其朋友却不能说同样的情况。更具体地说,它会很高兴地更改常量的值(例如,final
字段,或在类方法中从未修改的private
字段),但由于常量内联旧值可能会继续使用。Here's a little sample:
Running this little program outputs:
A few observations:
For static fields the supplied object to
Field.get()
can benull
.For brevity, I used an exception catch-all with the base
Exception
class - you should use explicit exception classes in your code.While
Field.get()
usually works as expected, the same cannot be said forField.set()
and its friends. More specifically it will happily change the value of a constant (e.g. afinal
field, or aprivate
field that is never modified in the class methods), but due to constant inlining the old value may remain in use.假设这些常量位于静态字段中:
输出为:
请注意 获取静态字段的值,您提供
null
作为参数。Assuming these constants are in static fields:
The output is:
Note that to get the value of a static field, you supply
null
as the arg.您可以通过类而不是对象引用了解修饰符。
http://download.oracle.com/javase/tutorial/reflect/class /classModifiers.html
You get to know about the modifiers via the class and not the object reference.
http://download.oracle.com/javase/tutorial/reflect/class/classModifiers.html