Get field values in Runtime
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
,
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.开发者_StackOverflow社区
arg
(called obj
in the Javadoc) is the instance on which to operate. In your example, the instance is bd
, so use f.getInt(bd)
to extract an int
field and so on.
精彩评论