できることは、インスタンス化コードをスーパークラスに記述し、それを特定のジェネリック型ごとに拡張することです (サブクラスではコードはほとんどまたはまったく必要ありませんが、型の消去を回避する唯一の方法であるため、サブクラスは必須です)。
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...") {}
これが最初の目標に最も近いと思います...