我有两个带嵌套泛型的类。有没有办法消除“类型不匹配:无法将
Msg<Value<String>>
转换为Msg<Value<?>>
”错误?在最后一次赋值中。public class Value<V> {
V val;
public Value(V val) {
this.val = val;
}
@Override
public String toString() {
return "" + val;
}
}
public class Msg<T> {
T holder;
public Msg( T holder) {
this.holder = holder ;
}
public String toString() {
return "" + holder;
}
public static void main(String[] args) {
Msg<Value<String>>strMsg = new Msg(new Value<String>("abc"));
// This is OK
Msg<?>objMsg = strMsg;
// Type mismatch: cannot convert from Msg<Value<String>> to Msg<Value<?>>
Msg<Value<?>>objMsg = strMsg;
}
}
static
工厂方法来代替构造函数;这样,每次使用new
时就不必为Msg
和Value
进行参数化。请注意,在原始代码片段中,您忘记了为new Msg
进行参数化,并使用了原始类型。请参阅此问题以了解类型推断的static
工厂方法可以为您做什么:https://dev59.com/L3A65IYBdhLWcg3w9DqF - polygenelubricants