당신이 할 수있는 일은 수퍼 클래스에 인스턴스화 코드를 작성한 다음 각 일반 제네 타입에 대해 인스턴스화 코드를 작성하는 것입니다 (서브 클래스에는 코드가 거의 또는 전혀 필요하지 않지만 서브 클래스는 유형을 피할 수있는 유일한 방법이기 때문에 필수입니다). 삭제) :
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