java - ClassCastException while trying to get the generic type parameter -
i want instance of generic using reflection:
this.wrapperinstance = ((class<wrapper>) ((parameterizedtype) (getclass().getgenericsuperclass())).getactualtypearguments()[1]).newinstance();
but exception:
java.lang.classcastexception: java.lang.class cannot cast java.lang.reflect.parameterizedtype
do not know problem, maybe someaone can me? there full class code:
public class xmlutils<model extends abstractmodel, wrapper extends wraperinterface<model>> { private wrapper wrapperinstance; @suppresswarnings("unchecked") public xmlutils() throws instantiationexception, illegalaccessexception { this.wrapperinstance = ((class<wrapper>) ((parameterizedtype) (getclass().getgenericsuperclass())).getactualtypearguments()[1]).newinstance(); } @suppresswarnings("unchecked") public list<model> loaddatafromxml(string filename) { try { file pajamufile = new file( userdataloader.instance.getcurrentuserfolder() + filename); jaxbcontext context = jaxbcontext.newinstance(wrapperinstance.getclass()); unmarshaller um = context.createunmarshaller(); wrapper wrapper = (wrapper) um.unmarshal(pajamufile); return wrapper.getdatalist(); } catch (jaxbexception e) { e.printstacktrace(); return new arraylist<model>(); } } public void savedatatoxml(list<model> datalist, string filename) { try { file pajamufile = new file( userdataloader.instance.getcurrentuserfolder() + filename); jaxbcontext context = jaxbcontext.newinstance(wrapperinstance.getclass()); marshaller m = context.createmarshaller(); wrapper wrapper = wrapperinstance; wrapper.setdatalist(datalist); m.marshal(wrapper, pajamufile); } catch (jaxbexception e) { e.printstacktrace(); } }
}
in google find such situation spring, here not using spring, maybe there clear solution want do.
do not know problem, maybe someaone can me
the error message self explanatory. following statement returns class
:
(getclass().getgenericsuperclass())
and trying cast parameterizedtype
((parameterizedtype) (getclass().getgenericsuperclass()))
class
, parameterizedtype
siblings. brother not sister trying cast them 1 cruel.
that being said, quick solution problem ask client code pass class
type xmlutils
class.
public class xmlutils<model extends abstractmodel, wrapper extends wraperinterface<model>> { private wrapper wrapperinstance; public xmlutils(class<wrapper> wrapperinstance) throws instantiationexception, illegalaccessexception { this.wrapperinstance = wrapperinstance } //more code follows }
Comments
Post a Comment