簡體   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