Java generics: capture generic type when copying instances of subclasses -
in following code sample, there way avoid ugly suppresswarnings annotations?
the code tests if parameter t instance of a , returns instance of a if so. satisfies general contract of createcopy() return object of same type parameter, safe operation. same goes test b.
i know wildcard capture , helper methods i'm not sure if , how helps in situation although problem appears quite similar.
abstract class base { public static <t extends base> t createcopy(t t) { if (t instanceof a) { @suppresswarnings("unchecked") t copy = (t) new a((a) t); return copy; } if (t instanceof b) { @suppresswarnings("unchecked") t copy = (t) new b((b) t); return copy; } throw new illegalstateexception(); } } class extends base { public a() { } public a(a a) { } } class b extends base { public b() { } public b(b b) { } }
you can pass class method, that's still ugly:
abstract class base { public static <t extends base> t createcopy(final t t, final class<t> klass) { if (t instanceof a) { final t copy = klass.cast(new a((a) t)); return copy; } if (t instanceof b) { final t copy = klass.cast(new b((b) t)); return copy; } throw new illegalstateexception(); } } class extends base { public a() { } public a(final a) { } } class b extends base { public b() { } public b(final b b) { } }
calling t.getclass()
doesn't work either. reason t can subtype of or b (that's why code not type-safe).
edit : why code not type-safe: imagine class aa
extends a
. if call method instance of class, create object of type a
, try cast aa
.
Comments
Post a Comment