java - How to get an enum constant from the first matching enum type -
note: question more generics enums.
i have few enum types, implementing common interface ieffect.
for example
enum elementaleffect implements ieffect { fire, water; } enum combateffect implements ieffect { paralysis, sleep; } i parse config-file, should add effects weapon. have resolve given name 1 of effects. keep simple maintain, thought of writing method (mostly pseudo-code, not compile. in fact point of question how make compile):
ieffect resolveeffectname(string name, class... clazzes) { for(class clazz : clazzes) { try { return enum.valueof(clazz, name); } catch(illegalargumentexception) { /* ignore, try next class */} } throw new illegalargumentexception("no matching effect found " + name); } // resolveeffectname(readnamefromfile, elementaleffect.class, combateffect.class); now problem have can't figure out how write method without compiler telling me
the method
valueof(class<t>, string)in type enum not applicable arguments ...
people saying should be
private static icombateffecttype getfirstresolved(string name, class<? extends enum<?>>... classes) { (class<? extends enum<?>> clazz : classes) { try { return enum.valueof(clazz, name); } catch (illegalargumentexception e) { } } return null; } this not working. feel free try (if don't believe me).
the method
valueof(class<t>, string)in type enum not applicable arguments(class<capture#6-of ? extends enum<?>>, string)
you can write fluently, if that's style:
class fluentgetter { private final string name; private ieffect found; fluentgetter(string name) { this.name = name; } <t extends enum<t> & ieffect> fluentgetter search(class<t> clazz) { if (found == null) { // if you've found something, don't overwrite that. try { found = enum.valueof(clazz, name); } catch (illegalargumentexception e) {} } return this; } ieffect get() { return found; // + check if it's null, if want. } } then:
ieffect effect = new fluentgetter(name) .search(elementaleffect.class) .search(combateffect.class) .get(); this avoids problem of generic bounds on array of classes having separate method calls each.
pretty sure wouldn't use myself; tossing out option.
Comments
Post a Comment