泛型和非泛型类的类型推断和泛型构造函数

时间:2019-05-12 16:03:48

标签: java generics

我正在阅读以下内容, https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html 尤其是“泛型和非泛型类的类型推断和泛型构造函数”部分。

我尝试运行以下内容:

public class MyClass < X > {

X myObject;

<T> MyClass(T t, X x) {
    myObject = x;
    System.out.println("t is " + x.getClass().getName());
    System.out.println("x is " + t.getClass().getName());
    System.out.println("myObject is " + myObject.getClass().getName());

    System.out.println("t value is " + t);
    System.out.println("x value is " + x);
    System.out.println("myObject value is " + myObject);

    myObject = new Integer(t); // 1 
}

public static void main(String[] args) {
    String myString = "1";
    MyClass<Integer> myObject = new MyClass<>(myString, new Integer(myString));
}

}

但出现以下编译错误:

$javac -Xdiags:verbose MyClass.java 
MyClass.java:15: error: no suitable constructor found for Integer(T)
        myObject = new Integer(t); // 1 
                   ^
    constructor Integer.Integer(int) is not applicable
      (argument mismatch; T cannot be converted to int)
    constructor Integer.Integer(String) is not applicable
      (argument mismatch; T cannot be converted to String)
  where T,X are type-variables:
    T extends Object declared in constructor <T>MyClass(T,X)
    X extends Object declared in class MyClass
1 error

如果我评论// 1,则没有错误,输出为

t is java.lang.Integer
x is java.lang.String
myObject is java.lang.Integer
t value is 1
x value is 1
myObject value is 1

有人可以告诉我发生了什么以及为什么会出错吗?

1 个答案:

答案 0 :(得分:2)

从编译器的角度来看:

T不是String希望传入的Integer.parseInt(...)

然后Integer.parseInt(...)将返回一个int而不是X