简体   繁体   English

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

[英]Invoking class constructor by explicitly specifying type witness

Oracle docs on Java generics type inference gives this exmaple: Oracle关于Java泛型类型推断的文档给出了以下示例:

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

Consider the following instantiation of the class MyClass: 考虑类MyClass的以下实例化:

new MyClass<Integer>("")

The statement explicitly specifies the type Integer for the formal type parameter, X . 该语句为形式类型参数X明确指定类型Integer The compiler infers the type String for the formal type parameter, T , because the actual parameter of this constructor is a String object. 编译器会为形式类型参数T推断String类型,因为此构造函数的实际参数是String对象。

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. 这就是您的代码无法正常工作的原因。

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 . Box<String,Integer>表示Box类型,其通用类型参数T等于StringS等于Integer Right? 对?

By replacing known generic arguments, the constructor's signature for Box<String, Integer> is: 通过替换已知的通用参数, Box<String, Integer>的构造函数签名为:

<X> Box(Integer p1, X p2)

This is how you call the constructor: 这是调用构造函数的方式:

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

You gave it a String as the first argument, but the constructor expects an Integer . 您给它一个String作为第一个参数,但是构造函数需要一个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. 交换两个泛型类型参数的位置,或者在调用构造函数时交换参数的位置。

To answer your question: 要回答您的问题:

how can I do this by explicitly specifying type witness... 我如何通过显式指定见证人来做到这一点...

You put in angle brackets between the new and the class name: 您在new名称和类名称之间放入尖括号:

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

But that is not the problem with your code, as Sweeper's answer shows. 但是,正如Sweeper的答案所示,这不是代码的问题。

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

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