Re: Accessibility of suBclass-fields from suPERclass (reflection)
On 8/17/2014 2:04 PM, Andreas Leitgeb wrote:
Eric Sosman <esosman@comcast-dot-net.invalid> wrote:
On 8/16/2014 6:37 PM, Andreas Leitgeb wrote:
I have a special Base class, and each of its subclasses serve exactly
one purpose: a collection of name/value associations where the java-
compiler knows about the valid names, so as to detect accesses to
non-existing names already at compile-time. (without that last premise,
I would have used HashMaps instead of subclasses)
Would an EnumMap serve?
In principle yes, but...
... element-access would look like:
someSpecificEnumMapInstance.get( SomeSpecificEnum.itemName )
instead of:
someSpecificSubClassInstance.itemName
We can all bemoan Java's occasional wordiness, but wasn't your
original code something like
Value value;
try {
Field f = someSpecificSubClassInstance
.getClass().getField("itenName");
f.setAccessible(true); // if needed
value = (Value) f.get(someSpecificSubClassInstance);
} catch (NoSuchFieldException | SecurityException | ... ex) {
throw SelfInflictedWoundException(ex);
}
? This is way wordier than using an EnumMap, *and* it prevents rather
than enables compile-time checking -- did you spot the typo?
I'm confident that you've got a credible use case, but I'm less
confident that you've got a credible use case for this technique. If
you'd reveal a little more about the larger problem, perhaps someone
could suggest an alternative approach -- that might even turn out to
be a better choice all around.
--
esosman@comcast-dot-net.invalid