membersound
membersound

Reputation: 86747

How to grant access on all private fields values retrieved by reflection?

Is it possible to get a fields' value, without using field.setAccessible(true);?

 Field field = object.getClass().getDeclaredField(fieldName);    
 field.setAccessible(true);
 Object value = field.get(object);

I mean, could I simply grant access to all private fields of a specific class, without having to invoke the setter on each read?

Upvotes: 0

Views: 1013

Answers (2)

Holger
Holger

Reputation: 298153

You don’t have to repeat that operation for every field access. You only have to do it once per class/field, but there is an efficient way to do it:

static final class Accessor extends ClassValue<Map<String,Field>> {
    @Override protected Map<String, Field> computeValue(Class<?> type) {
        Field[] fields=type.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        Map<String,Field> map=new HashMap<>(fields.length);
        for(Field f: fields) map.put(f.getName(), f);
        return map;
    }
}
static final Accessor FIELD_ACCESSOR = new Accessor();

which makes your access as simple as

Object value = FIELD_ACCESSOR.get(o.getClass()).get(fieldName).get(o);

Note that ClassValue takes care of performing the operation only once per class, while the cached values do not prevent class garbage collection, and AccessibleObject.setAccessible(…) will be applied to all declared fields at once.

But keep in mind, that these are the declared fields of the actual class only, you will have to iterate the super class hierarchy manually to search their fields. Field names don’t have to be unique through the class hierarchy.

Upvotes: 4

kan
kan

Reputation: 28951

No, you could not. What's for? You could prepare Field object(s) once, cache it and use it for reading multiple times.

 // do it once
 Field field = object.getClass().getDeclaredField(fieldName);    
 field.setAccessible(true);

 // use many times:
 for(million times)
     Object value = field.get(object);

Upvotes: 1

Related Questions