• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics and class literals  RSS feed

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following example:
This fails with two compiler errors:
If I change Class<? extends Base<?>> into Class<? extends Base> then it works, except Eclipse shows a warning:
Base is a raw type. References to generic type Base<T> should be parameterized

Since I want something like this in one of my APIs I want to handle this as cleanly as possible. Right now I have my method return Set<Class<? extends Base<?>>> which causes class literals for all generic sub types to require an explicit cast (which I have to suppress with @SuppressWarnings("unchecked")). The alternative is make the method return Set<Class<? extends Base>> but then my API includes use of a raw type (which I have to suppress with @SuppressWarnings("rawtypes") in both the interface and implementations). Either way I have to suppress warnings.

Does anyone have suggestions on how to fix this in the cleanest way? Or have I already chosen the cleanest way?
 
Joe Bishara
Ranch Hand
Posts: 175
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't I think that it's possible to get rid of the compiler warnings because Base.class and GenericSub.class are raw types.

Class<? extends Base<?>> cls2 = NonGenericSub.class;

does not generate a compiler warning because NonGenericSub.class is not a raw type.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And unfortunately there's no way to make a class literal of a parameterized type, because of erasure:

Why is there no class literal for concrete parameterized types?
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I already suspected I have to choose one or the other for ignoring warnings, I just hoped there was a better way.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!