繁体   English   中英

通过显式指定类型见证人来调用类构造函数

[英]Invoking class constructor by explicitly specifying type witness

Oracle关于Java泛型类型推断的文档给出了以下示例:

class MyClass<X> {
  <T> MyClass(T t) {
    // ...
  }
}

考虑类MyClass的以下实例化:

new MyClass<Integer>("")

该语句为形式类型参数X明确指定类型Integer 编译器会为形式类型参数T推断String类型,因为此构造函数的实际参数是String对象。

我试图尝试一下。 我定义了以下课程:

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

上面对构造函数的调用给了我编译时错误:

The constructor Box<String,Integer>(String, int) is undefined

我知道我可以通过指定菱形来做到这一点:

Box box4 = new Box<>("Mahesh",11);

但是只是很好奇,我该如何通过显式指定见证人做到这一点...

这就是您的代码无法正常工作的原因。

Box<String,Integer>表示Box类型,其通用类型参数T等于StringS等于Integer 对?

通过替换已知的通用参数, Box<String, Integer>的构造函数签名为:

<X> Box(Integer p1, X p2)

这是调用构造函数的方式:

new Box<String,Integer>("Mahesh",11)

您给它一个String作为第一个参数,但是构造函数需要一个Integer 编译器错误!

您有很多方法可以解决此问题。 交换两个泛型类型参数的位置,或者在调用构造函数时交换参数的位置。

要回答您的问题:

我如何通过显式指定见证人来做到这一点...

您在new名称和类名称之间放入尖括号:

new <TypeWitnessForConstructor> Box<TypeArgumentsForInstance>(...)

但是,正如Sweeper的答案所示,这不是代码的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM