Java: generic enum in method parameter -
correspondig following question:
java: enum parameter in method
i know, how can format code require enums generically.
foo.java
public enum foo { a(1), b(2); }
bar.java
public class bar { public bar(generic enum); }
later on i'll have more enum classes "foo", can still create bar containing kind of enum class. have "jdk1.6.0_20" way...
see methods in enumset reference, e.g.
public static <e extends enum<e>> enumset<e> of(e e)
(this method returns enumset 1 element given enum element e)
so generic bounds need are: <e extends enum<e>>
actually, make bar
generic:
public class bar<e extends enum<e>> { private final e item; public e getitem(){ return item; } public bar(final e item){ this.item = item; } }
you may add factory method from
, with
etc.
public static <e2 extends enum<e2>> bar<e2> with(e2 item){ return new bar<e2>(item); }
that way, in client code have write generic signature once:
// e.g. simple version bar<myenum> bar = bar.with(myenum.some_instance); // instead of more verbose version: bar<myenum> bar = new bar<myenum>(myenum.some_instance);
reference:
Comments
Post a Comment