在运行时获取字段值
如何获取Java Runtime中字段的值?
编辑:
使用这种结构:
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(
false);
for (BeanDefinition bd : scanner
.findCandidateComponents("aspectlogging"))
{
Class myTarget = null;
try {
myTarget = Class.forName(bd.getBeanClassName());
}
catch (ClassNotFoundException e) {...}
for (Field f:myTarget.getDeclaredFields()){
try {
System.out.println("FIELD: " + f.get(myTarget));
} catch (IllegalArgumentException e) {...}
catch (IllegalAccessException e) {...}
} }
当调用f.get(myTarget)
时,我得到java.lang.IllegalAccessException
,
,< br> 其中,myTarget
是运行时获取的 bean 实例,f
是它的字段。
当在循环中运行以下时:
System.out.println("FIELD: " + f);
得到字段名称 确定:
FIELD: private java.lang.String aspectlogging.TestableBean.name
FIELD: private java.lang.String aspectlogging.TestableBean.name
很奇怪,无法获取该值。
How to get value of the field in Runtime for Java?
EDIT:
using this construction:
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(
false);
for (BeanDefinition bd : scanner
.findCandidateComponents("aspectlogging"))
{
Class myTarget = null;
try {
myTarget = Class.forName(bd.getBeanClassName());
}
catch (ClassNotFoundException e) {...}
for (Field f:myTarget.getDeclaredFields()){
try {
System.out.println("FIELD: " + f.get(myTarget));
} catch (IllegalArgumentException e) {...}
catch (IllegalAccessException e) {...}
} }
I've got java.lang.IllegalAccessException
,
when call f.get(myTarget)
,
where myTarget
is the instance of bean got in Runtime and f
is its field.
when run in loop following:
System.out.println("FIELD: " + f);
got field names OK:
FIELD: private java.lang.String aspectlogging.TestableBean.name
FIELD: private java.lang.String aspectlogging.TestableBean.name
It's quite strange,that value can't be got.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
arg
(在 Javadoc 中称为obj
) 是要操作的实例。在您的示例中,实例是bd
,因此使用f.getInt(bd)
提取int
字段等。arg
(calledobj
in the Javadoc) is the instance on which to operate. In your example, the instance isbd
, so usef.getInt(bd)
to extract anint
field and so on.