Feature suggestion: Allow generic wildcard in class literal expression
some-java-user-99206970363698485155 at vodafonemail.de
some-java-user-99206970363698485155 at vodafonemail.de
Fri Jan 4 23:01:14 UTC 2019
JDK-6184881 describes that Object.getClass() should ideally not return classes of raw types anymore but instead use wildcards. The problem is that, as noted in the comments, this breaks compability with previously written code and therefore this change is not very likely (at the moment?).
However, the report does not cover the class literal expression (https://docs.oracle.com/javase/specs/jls/se11/html/jls-15.html#jls-15.8.2).
It would be good to allow the usage of the wildcard (`?`) for this expression:
List<?>.class => Class<List<?>>
Since it is currently not allowed to provide type parameters in the class literal expression there should not be any compatibility issues.
Additionally if at some point JDK-6184881 is fixed for class literals as well, then the expression List<?>.class could just be a verbose variant of List.class without causing any problems either.
This would make writing methods or constructors which determine a generic type based on a given class easier for generic classes, e.g.:
public class MyContainer<T> {
private final Class<T> valueClass;
public MyContainer(Class<T> valueClass) {
this.valueClass = valueClass;
}
public static void main(String[] args) {
MyContainer<String> stringContainer = new MyContainer<>(String.class);
// Have to use raw type (or verbose casting of class)
MyContainer<List> listContainer = new MyContainer<>(List.class);
// With suggested change:
MyContainer<List<?>> listContainer = new MyContainer<>(List<?>.class);
}
}
More information about the core-libs-dev
mailing list