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;
}
}
Run Code Online (Sandbox Code Playgroud)
required:
找到的类:类型参数
是否有可能以其他方式初始化first
/ second
with(with-arguments)U/V类型的构造函数?
由于类型擦除, Java通常不允许这样做.您可以指定类型的构造函数参数,Class<U>
并Class<V>
为其传递给定类型参数的具体类类型(即Integer.class
和String.class
for <Integer>
和<String>
).
也可以使用字节码级反射来提取类型,但是非常复杂,并且它并不总是适用于所有情况.如果您向下滚动本文,您可以找到使这成为可能的示例.为方便起见,我在下面贴了它.
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];
}
Run Code Online (Sandbox Code Playgroud)
编辑:回复评论:
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;
}
}
Run Code Online (Sandbox Code Playgroud)