3 回答
TA贡献1802条经验 获得超5个赞
public class MyGenericClass<T> { private final Class<T> clazz; public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) { return new MyGenericClass<U>(clazz); } protected MyGenericClass(Class<T> clazz) { this.clazz = clazz; } public void doSomething() { T instance = clazz.newInstance(); }}
TA贡献1790条经验 获得超9个赞
我刚刚提到了这个解决方案:
import java.lang.reflect.ParameterizedType;
public abstract class A<B> {
public Class<B> g() throws Exception {
ParameterizedType superclass =
(ParameterizedType) getClass().getGenericSuperclass();
return (Class<B>) superclass.getActualTypeArguments()[0];
}
}
如果A由子类提供具体类型:
new A<String>() {}.g() // this will work
class B extends A<String> {}
new B().g() // this will work
class C<T> extends A<T> {}
new C<String>().g() // this will NOT work
TA贡献1831条经验 获得超9个赞
g()
A
private Class<?> extractClassFromType(Type t) throws ClassCastException { if (t instanceof Class<?>) { return (Class<?>)t; } return (Class<?>)((ParameterizedType)t).getRawType();}public Class<B> g() throws ClassCastException { Class<?> superClass = getClass(); // initial value Type superType; do { superType = superClass.getGenericSuperclass(); superClass = extractClassFromType(superType); } while (! (superClass.equals(A.class))); Type actualArg = ((ParameterizedType)superType).getActualTypeArguments()[0]; return (Class<B>)extractClassFromType(actualArg);}
public class Foo<U,T extends Collection<?>> extends A<T> {}(new Foo<String,List<Object>>() {}).g();
ClassCastException
Class
ParameterizedType
TypeVariable
T
T
添加回答
举报