java - Why is Class<?> preferred to Class -
if declare class field:
class fooclass; eclipse gives me warning:
class raw type. references generic type class should parametrized
what mean in practice? , why urged it? if ask eclipse "quick fix" gives me:
class<?> fooclass; which doesn't seem add value no longer gives warning.
edit: why class generic? please give example of parameterization, i.e. there valid use of other <?> ?
edit: wow! had not realized depths of this. have watched java puzzler , it's scared me bear traps. use
class<mystring> mystringclass = mystring.class; rather
class mystringclass = mystring.class; (but having used java day one, didn't notice when class became generic);
note: have accepted @oxbow_lakes makes sense me, complicated area. urge programmers use specific class<mystring> rather class. , class<?> safer class.
raw types , unbounded wildcards
none of previous answers have addressed why should prefer class<?> on class, on face of it, former seems offer no more information latter.
the reason that, raw type, i.e. class, prevents compiler making generic type checks. is, if use raw types, you subvert type-system. example:
public void foo(class<string> c) { system.out.println(c); } can called thusly (it both compile and run):
class r = integer.class foo(r); //this ok (but shouldn't be) but not by:
class<?> w = integer.class foo(w); //will not compile (rightly so!) by using non-raw form, when must use ? because cannot know type parameter (or bounded by), allow compiler reason correctness of program more if used raw types.
why have raw types @ all?
the java language specification says:
the use of raw types allowed concession compatibility of legacy code
you should avoid them. unbounded wildcard ? best described elsewhere means "this parameterized on type, not know (or care) is". not same raw types, abomination , not exist in other languages generics, scala.
why class parameterized?
well, here use-case. suppose have service interface:
public interface fooservice and want inject implementation of it, using system property define class used.
class<?> c = class.forname(system.getproperty("foo.service")); i not know @ point class, of correct type:
//next line throws classcastexception if c not of compatible type class<? extends fooservice> f = c.assubclass(fooservice.class); now can instantiate fooservice:
fooservice s = f.newinstance(); //no cast
Comments
Post a Comment