Java Compile error when return Generic Class type -


public interface parent{ }  public class child implements parent{ }  public <t extends parent> class<t> getclass(){   return child.class;  // compile error, add cast class<t> } 

i expect there no error above code, compile error when return child.class.

you can't tell java return child.class regardless of t. there might other classes extending parent aren't child. also, since not using t anywhere, code doesn't make sense. 2 possible solutions:

public class<? extends parent> getaclass() {     return child.class; } 

or perhaps

public <t extends parent> class<t> getaclass(class<t> clazz){     return clazz;  } 

the second example compiles, make more sense if t declared @ class level.

also, renamed method avoid name clash existing getclass() method.


Comments