你可以做的是在超类中编写实例化代码,然后对每个特定的泛型类型进行扩展(在子类中需要很少或没有代码,但是子类是必需的,因为它们是避免类型的唯一方法擦除):
abstract class MyGeneric<T> {
private T instance;
public MyGeneric(String str) {
// grab the actual class represented by 'T'
// this only works for subclasses of MyGeneric<T>, not for MyGeneric itself !
Class<T> genericType = (Class<T>) ((ParameterizedType)getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
try {
// instantiate that class with the provided parameter
instance = genericType.getConstructor(String.class).newInstance(str);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
}
class MyUser extends MyGeneric<User> {
public MyUser() {
// provide the string to use for instantiating users...
super("userStr");
}
}
class User { /*...*/ }
编辑:由通用类abstract
强制子类的用法。
它也可以用匿名类等一起使用:
new MyGeneric<User>("..string...") {}
我觉得这是最接近您最初的目标,你可以得到...
为什么?这不会允许MyGeneric使用T的方法。MyGeneric只能使用T的上界方法。 – ignis