java - Create enum with entries associated to classes -
supposing have several specific classes extend 1 abstract class, so:
public abstract abstractclass { // abstract stuff here } public firstspecificclass extends abstractclass { // specific stuff here } public secondspecificclass extends abstractclass { // specific stuff here }
i need create enum
elsewhere in each entry connected (associated?) 1 of specific classes; end, passing specific class constructor parameter , storing private field within enum (i've provided getter method field). need create static method takes instance of 1 of specific classes argument , returns appropriate enum element (or null). looping on each enum entry , using instanceof
in combination getter private field mentioned previously. attempt:
public enum types { first(firstspecificclass.class), // line 2 second(secondspecificclass.class); // line 3 private class<abstractclass> classtype; private types(class<abstractclass> classtype) { this.classtype = classtype; } public class<abstractclass> getclasstype() { return this.classtype; } public static types fromtypeinstance(abstractclass instance) { for(types t : types.values()) if(instance instanceof t.getclasstype()) return t; // line 17 return null; } }
i seem misunderstanding how store class type field can returned , used in instanceof
check later. code producing several compile-time errors:
- (line 2 of enum): constructor
types(class<firstspecificclass>)
undefined - (line 3 of enum): constructor
types(class<secondspecificclass>)
undefined - (line 17 of enum): incompatible operand types
boolean
,class<abstractclass>
i not java programmer, , understanding of generics , instanceof
fuzzy @ best, although have pretty firm grasp on concept of oop. how can resolve these errors , achieve desired effect?
in java, generics invariant. means class<firstspecificclass>
not class<abstractclass>
, if firstspecificclass
abstractclass
.
you can work around explicitly allowing subtypes upper bound wildcard. add ? extends
before abstractclass
type argument needed.
private class<? extends abstractclass> classtype; private types(class<? extends abstractclass> classtype) { this.classtype = classtype; } public class<? extends abstractclass> getclasstype() { return this.classtype; }
additionally, must specify type directly in source code instanceof
operator, doesn't compile:
if(instance instanceof t.getclasstype())
you can use class
object's isinstance
method instead, runtime solution:
if(t.getclasstype().isinstance(instance))
Comments
Post a Comment