gpt4 book ai didi

java - 初始化变量。我不知道他们的类型 [java]

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:57:22 25 4
gpt4 key购买 nike

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;
}
}

必填:类
发现:类型参数

是否可以通过其他方式使用 U/V 类型的(不带参数的)构造函数初始化 first/second

最佳答案

Java 通常不允许这样做,因为 type erasure .您可以指定 Class<U> 类型的构造函数参数和 Class<V> ,为此您将传递给定类型参数的具体类类型(即 Integer.classString.class 用于 <Integer><String>)。

也可以使用字节码级别的反射来提取类型,但是相当复杂,而且它并不总是适用于所有情况。如果向下滚动 this article ,您可以找到使这成为可能的示例。为方便起见,我将其粘贴在下方。

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 - 初始化变量。我不知道他们的类型 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6718330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com