主要的:
public class Main {
public static void main(String [] args) {
Foo<String, Location> foo = new Foo<>();
foo.add("abc", new Location(5, 6));
}
}
地點:
public class Location {
public int x;
public int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" x "," y ")";
}
}
福類:
public class Foo<K, T> {
public void add(K name, T loc) {
System.out.println(name " " loc.x loc.y);
}
}
當我嘗試運行該程式時,出現“問題標題”錯誤,我不知道會發生什么,也不知道如何解決。
uj5u.com熱心網友回復:
一種方法是使用instanceof運算子,如果您需要一個您知道的型別。這是一個演示。
public void add(K name, T loc) {
if(loc instanceof Location) {
System.out.println(name " " ((Location)loc).x ((Location)loc).y);
}
}
更新
正如 Stephen C 提到的,Fooclass 可能需要對每種可能型別的功能進行硬編碼的知識T。這是(理論上)每個 Java 參考型別!解決這個問題的正確方法是<T extends SomeInterface>在介面中宣告并提供getter來獲取x和y屬性
因此,而不是知道有關的所有可能的型別T,我們可以T擴展SomeInterface,并通過呼叫它可以在相應的實施的干將獲得的資訊type。
制作T擴展LocationInfo介面以獲取有關 x 和 y 的資訊
class Foo<K, T extends LocationInfo> {
public void add(K name, T loc) {
System.out.println(name " " loc.getX() loc.getY());
}
}
interface LocationInfo {
int getX();
int getY();
}
并在Location類中包含實作
class Location implements LocationInfo {
public int x;
public int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "(" x "," y ")";
}
public int getX() { return x; }
public int getY() { return y; }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375643.html
