class pair<U,V>{
U first;
V second;
public pair() {
first = new U(); //error
second = new V(); //error
}
public pair(U f,V s){
first = f;
second = s;
}
}
所需内容:class
找到内容:类型参数
是否可以使用U/V类型的(无参数)构造函数以另一种方式初始化first
/second
?
由于 类型擦除,Java通常不允许这样做。您可以指定类型为Class<U>
和Class<V>
的构造函数参数,针对给定类型参数的具体类类型传递(即Integer.class
和String.class
用于<Integer>
和<String>
)。请注意保留HTML标记。
也可以使用字节码级别的反射提取类型,但这相当复杂,并且并不总是在所有情况下都有效。如果您在此文章上向下滚动,可以找到使此操作成为可能的示例。为方便起见,我已将其粘贴在下面。
static public Type getType(final Class<?> klass, final int pos) {
// obtain anonymous, if any, class for 'this' instance
final Type superclass = klass.getGenericSuperclass();
// test if an anonymous class was employed during the call
if ( !(superclass instanceof Class) ) {
throw new RuntimeException("This instance should belong to an anonymous class");
}
// obtain RTTI of all generic parameters
final Type[] types = ((ParameterizedType) superclass).getActualTypeArguments();
// test if enough generic parameters were passed
if ( pos < types.length ) {
throw RuntimeException(String.format("Could not find generic parameter #%d because only %d parameters were passed", pos, types.length));
}
// return the type descriptor of the requested generic parameter
return types[pos];
}
编辑:针对评论的回复:
class pair<U,V>{
U first;
V second;
public pair(Class<U> cu, Class<V> cv) {
try {
first = cu.newInstance();
second = cv.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public pair(U f,V s){
first = f;
second = s;
}
}
不行,Java中类型会被擦除。所以你应该将构造函数移到调用处。