How can I use a Java 8 default method in an interface to extract the Class of a Parameterized Type instead of using an abstract class?
Option 1 (Fails):
public interface EpicCoolInterface<T> {
default Class<T> getParameterizedTypeClass() {
return T.class; //doesn't work
}
Option 2 (Fails):
public interface EpicCoolInterface<T> {
default Class<T> getParameterizedTypeClass() {
return (Class<T>) ((ParameterizedType) getClass().getGenericInterfaces()[0])
.getActualTypeArguments()[0];
//java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
}
Third attempt (successful but no interface):
public abstract class CoolAbstractClass<T> {
private Class<T> clazz;
public CoolAbstractClass() {
try {
this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Class<T> getType() {
return clazz;
}
}
Aucun commentaire:
Enregistrer un commentaire