Make a Java class generic, but only for two or three types -
(i astonished not able find question on stackoverflow, can put down poor googling on part, means point out duplicate...)
here toy class returns reverse of put it. works on integers, require minor changes work string.
public class mirror { int value; public int get() { return reverse(value); } private int reverse(int value2) { string valuestring = value + ""; string newstring = reverse(valuestring); return integer.parseint(newstring); } private string reverse(string valuestring) { string newstring = ""; (char c : valuestring.tochararray()) { newstring = c + newstring; } return newstring; } public void set(int value) { this.value = value; } }
what i'd make class generic, for, say, 2 or 3 possible types. want write is:
public class mirror<x, x 1 of integer, string, or magicvalue { x value public x get(){ [...]
what's correct syntax? google-fu failing me... :(
edit: appears there isn't correct syntax , can't appear done, main question is: why? seems sort of thing people might want before made class truly generic...
edit edit: managed work out why labmates today, added relevant why answer below.
unfortunately java not provide such functionality directly. can suggest following work around:
create parametrized class mirror
private constructor , 3 static factory methods create instance of mirror
specific parameter:
public class mirror<t> { private t value private mirror(t value) { this.value = value; } public static mirror<integer> integermirror(integer value) { return new mirror(value); } public static mirror<string> stringmirror(string value) { return new mirror(value); } public static mirror<magicvalue> magicmirror(magicvalue value) { return new mirror(value); } }
edit can (and should) separate class mirror
creating, e.g. put factory methods separate class mirrorfactory
. in case constructor should become package protected.
if want support large yet limited number of classes can implement 1 generic factory method
public static <t> mirror<t> createmirror(t value) { checktypesupported(value); return new mirror(value); }
method checktypesupported(value);
may use kind of metadatat (e.g. properties, json etc file) supported types. in case not enjoy compile time validation.
other solution require supported types extend base class or implement interface:
public class mirror<t extends myinterface> {}
but solution seems not match requirements since need integer
, string
, magicvalue
.
Comments
Post a Comment