sergionni
sergionni

Reputation: 13510

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,
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.

Upvotes: 1

Views: 1672

Answers (1)

NPE
NPE

Reputation: 500357

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.

Upvotes: 1

Related Questions