Java compilation error when returning 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 to Class<T> } 

I expect errors above the code, but I get a compilation error when I return Child.class.

+5
source share
3 answers

You cannot tell Java to always return Child.class regardless of T There may be other classes extending from the parent that are not Child . Also, since you are not using T anywhere, your code does not make much sense. Two possible solutions:

 public Class<? extends Parent> getAClass() { return Child.class; } 

or maybe

 public <T extends Parent> Class<T> getAClass(Class<T> clazz){ return clazz; } 

The second example compiles, but it probably makes sense if T was declared at the class level.

In addition, I renamed your method to avoid a name clash with the existing getClass() method.

+5
source

Check out the following

 public class Main { public interface Parent{} public class Child implements Parent{} public class BadChild implements Parent {} public static <T extends Parent> Class<T> getClazz() { return Child.class; // compile error, add cast to Class<T> } public static void main(String[] args) { Class<BadChild> clazz = Main.<BadChild>getClazz(); } } 

The call method getClazz() with type BadChild valid for the caller side. If you can compile your method that will lead to runtime errors. That is why it is forbidden.

+2
source

If this code was legal, you could write:

 Class<SomeOtherChildClass> clazz = instance.getAClass(); 

(assuming SomeOtherChildClass also extending Parent ), which would obviously fail at runtime for an existing implementation.

I am not suggesting a β€œfixed” code because I am not sure what you are trying to do.

+1
source

Source: https://habr.com/ru/post/1241789/


All Articles