Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Accessibility of suBclass-fields from suPERclass (reflection) Date: Sun, 17 Aug 2014 15:24:51 -0400 Organization: A noiseless patient Spider Lines: 44 Message-ID: References: <53eecf6a$0$300$14726298@news.sunsite.dk> Mime-Version: 1.0 Content-Type: text/plain; charset=windows-1252; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 17 Aug 2014 19:24:52 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="bd4e1cba8d8592bec5d5ed9e4537fbfd"; logging-data="29842"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/8lbvGEeC0tiXO30qwGC2+" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Thunderbird/31.0 In-Reply-To: Cancel-Lock: sha1:4xGSIUmycA+Q9GH02XVdkQHs9Gw= Xref: csiph.com comp.lang.java.programmer:29710 On 8/17/2014 2:04 PM, Andreas Leitgeb wrote: > Eric Sosman 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