java - How do I get the `.class` attribute from a generic type parameter? -
the accepted answer this question describes how create instance of t in generic<t> class. involves passing in class<t> parameter generic constructor , callin newinstance method that.
a new instance of generic<bar> created, , parameter bar.class passed in.
what do if generic type parameter new generic class not known class bar generic type parameter? suppose had other class skeet<j> , wanted create new instance of generic<j> inside class. then, if try pass in j.class following compiler error:
cannot select type variable. is there way around this?
the specific bit of code triggering error me is:
public class inputfield<w extends component & widgetinterface> extends inputfieldarray<w> { public inputfield(string labeltext) { super(new string[] {labeltext}, w.class); } /* ... */ } public class inputfieldarray<w extends component & widgetinterface> extends jpanel { /* ... */ public inputfieldarray(string[] labeltext, class<w> clazz) throws instantiationexception, illegalaccessexception { /* ... */ (int = 0 ; < labeltext.length ; i++) { newlabel = new jlabel(labeltext[i]); newwidget = clazz.newinstance(); /* ... */ } /* ... */ } /* ... */ } the error happens, because can't write w.class. there other way of passing in same information?
using .class on type parameter isn't allowed - because of type erasure, w have been erased component @ runtime. inputfield need take class<w> caller, inputfieldarray:
public inputfield(string labeltext, class<w> clazz) { super(new string[] {labeltext}, clazz); }
Comments
Post a Comment