你可以做的是在超類中編寫實例化代碼,然後對每個特定的泛型類型進行擴展(在子類中需要很少或沒有代碼,但是子類是必需的,因爲它們是避免類型的唯一方法擦除):
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