问题描述
有关Java泛型类型的Oracle文档给出了这一点例子:
class MyClass<X> {
<T> MyClass(T t) {
// ...
}
}
new MyClass<Integer>("")
该语句为形式类型参数X
明确指定类型Integer
.编译器会为形式类型参数T
推断类型String
,因为此构造函数的实际参数是String对象.
The statement explicitly specifies the type Integer
for the formal type parameter, X
. The compiler infers the type String
for the formal type parameter, T
, because the actual parameter of this constructor is a String object.
我试图对此进行试验.我定义了以下课程:
I tried to experiment with this. I defined following class:
class Box<T,S>
{
T item;
S otherItem;
<X> Box(S p1, X p2)
{
otherItem = p1;
}
public static void main(String[] args)
{
/* Below gives compile time error:
The constructor Box<String,Integer>(String, int) is undefined
*/
Box box4 = new Box<String,Integer>("Mahesh",11);
}
}
对构造函数的调用给了我编译时错误:
Above call to constructor gives me compile time error:
The constructor Box<String,Integer>(String, int) is undefined
我知道我可以通过指定菱形来实现:
I know I can do this by specifying the diamond:
Box box4 = new Box<>("Mahesh",11);
但是很好奇,我如何通过 明确指定类型见证人 ...
But just curious, how can I do this by explicitly specifying type witness...
推荐答案
这就是为什么您的代码无法正常工作的原因.
Here's why your code does not work.
用Box<String,Integer>
表示Box
类型,其通用类型参数T
等于String
,而S
等于Integer
.对吧?
By Box<String,Integer>
you mean a Box
type with the generic type parameter T
being equal to String
and S
being equal to Integer
. Right?
通过替换已知的通用参数,Box<String, Integer>
的构造函数签名为:
By replacing known generic arguments, the constructor's signature for Box<String, Integer>
is:
<X> Box(Integer p1, X p2)
这是调用构造函数的方式:
This is how you call the constructor:
new Box<String,Integer>("Mahesh",11)
您给它一个String
作为第一个参数,但是构造函数希望它是一个Integer
.编译器错误!
You gave it a String
as the first argument, but the constructor expects an Integer
. Compiler Error!
您可以通过多种方法来解决此问题.要么交换两个泛型类型参数的位置,要么在调用构造函数时交换参数的位置.
You have lots of ways to work around this. Either swap the positions of the two generic type arguments, or swap the positions of the arguments when calling the constructor.
这篇关于通过显式指定类型见证人来调用类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!