Reputation: 10026
The other day I was going over acl modules' source-code in spring-security (3.0.x branch) And I found that an ACLImpl object had a private set of ACE's (represented in db by a 1-many reflection). Going deeper in the code I found that there was no obvious point where the private set of ace's was populated. It took me a while to find that population was done with java.lang.reflect.Field
:
private final Field fieldAces = FieldUtils.getField(AclImpl.class, "aces");
...
fieldAces.setAccessible(true);
...
try {
fieldAces.set(acl, aces);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not set AclImpl entries", e);
}
(All code copied over from BasicLookupStrategy.java
)
I thought that Field was primarily used to disclose private fields in obscure jars. Are there any other reasons apart from obfuscating code-flow?
Upvotes: 0
Views: 94
Reputation: 3246
Aside from accessing private or otherwise inaccessible fields, java.lang.reflect.Field serves the same purpose as the whole reflection mechanism in general: to allow dynamic discovery and manipulation of types not necessarily known at the compile time. Java, as many other languages, is statically typed. Reflection mechanisms allows one to bypass it to some degree, and introduce some more dynamic features, like, say, retrieval of value of field by name. This is invaluable, as much of the "magic" performed by some tools that we take for granted relies on it - think JUnit, mocking frameworks, Hibernate, JAXP, gson... Obfuscating code-flow is but one of the plethora of wonderful things you can use java.lang.reflect.Field for :)
Upvotes: 2