java - usage of generics as return type -
i've structure this:
abstract class mydomain{...} abstract class foodomain extends mydomain{...} abstract class bardomain extends mydomain{...} class firstconcretebardomain extends bardomain{...} class secondconcretebardomain extends bardomain{...} i need factory creates mydomain objects. first attempt this:
public interface ispecializedobjectsfactory { public <t extends mydomain> t create(class<?> clazz); } implementend as:
public class firstspecializedobjectsfactory implements ispecializedobjectsfactory { @override public <t extends mydomain> t create(class<?> clazz) { if(clazz.equals(bardomain.class)) return new firstbardomain(); throw new invalidparameterexception(); } same secondbardomain.
first question: why generating error says cannot cast firstbardomain t?
after error i've introduced cast: return (t) new firstbardomain();.
the problem cast unsafe , want confident result, i've introduced constraint (assuming each mydomain object have 2 levels of derivation):
public <t extends anagrafedomain, s extends t> s create(class<t> clazz) second question: assuming factory entry point mydomain objects created, , calls factory never use concrete classes (but like: bardomain subj = specializedobjectsfactory.getfactory().create(bardomain.class);), question is: new version safe?
the reason cast unsafe because of particular line:
public <t extends mydomain> t create(class<?> clazz) { this infers return type call site; in other words, consider following class:
public abstract class myfakedomain extends mydomain { } the following code compile, fail @ runtime:
ispecializedobjectsfactory factory = new firstspecializedobjectsfactory(); myfakedomain broken = factory.create(bardomain.class); this throw classcastexception because of type inference; inferred type myfakedomain, resulting in attempt cast firstbardomain myfakedomain, illegal cast - hence unsafe warning.
the type inference reason why cast must present; whilst firstbardomain subclass of mydomain, not know if of type t, t any mydomain subclass, not firstbardomain.
however, if caller careful, code work fine - whether consider acceptable or not you.
this gives answer second question: using bardomain type inferred not safe, subclass of mydomain. type safe here mydomain - however, if planning on using mydomain type, might remove generic type bound , make return type mydomain.
Comments
Post a Comment