簡體   English   中英

如何使用Java泛型方法?

[英]How to use Java generics method?

我正在從C ++遷移到Java。 現在我正在嘗試一種泛型方法。 但編譯器總是抱怨下面的錯誤

方法getValue()未定義類型T HelloTemplate.java / helloTemplate / src / helloTemplate

錯誤指向t.getValue()行據我所知,T是類MyValue,其方法為getValue

怎么了? 我該如何解決這個問題。 我使用的是Java1.8

public class MyValue {

    public int getValue() {
       return 0;
    }
}

public class HelloTemplate {

    static <T> int getValue(T t) {
        return t.getValue();
    }
    public static void main(String[] args) {
       MyValue mv = new MyValue();
       System.out.println(getValue(mv));
   }

}

編譯器不知道您將傳遞給getValue()一個具有getValue()方法的類的實例,這就是t.getValue()不通過編譯的原因。

如果添加綁定到泛型類型參數T的類型,它只會知道它:

static <T extends MyValue> int getValue(T t) {
    return t.getValue();
}

當然,在這樣一個簡單的例子中,你可以簡單地刪除泛型類型參數並寫:

static int getValue(MyValue t) {
    return t.getValue();
}

只需要在調用方法之前進行轉換。 return ((MyValue) t).getValue(); ,以便編譯器可以知道它正在調用MyValue的方法。

   static <T> int getValue(T t) {
        return ((MyValue) t).getValue();
    }

在多個類的情況下,您可以使用instanceof運算符檢查instanceof ,並調用方法..如下所示

  static <T> int getValue(T t) {
        //check for instances
        if (t instanceof MyValue) {
            return ((MyValue) t).getValue();
        }
        //check for your other instance
  return 0; // whatever for your else case.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM