簡體   English   中英

帶有擴展名的泛型的正確Java語法

[英]correct java syntax for generics with extends

這是我在努力的一段代碼。

public class Channel<T extends Something>{
   public Channel(){}
   public void method(T something){}
}

public class Manager{
   private static ArrayList<Channel<? extends Something>> channels
         = new ArrayList<Channel<? extends Something>>();
   public static <T extends Something> void OtherMethod(T foo){
      for(Channel<? extends Something> c : channels)
        c.method(foo);  // this does not work
   }
}

不起作用的行給了我編譯器錯誤:

The method method(capture#1-of ? extends Something) in the type Channel<capture#1-of ? extends Something> is not applicable for the arguments (T)

我不明白這個錯誤。 如果我刪除Manager類中的所有泛型,則可以正常工作,但鍵入不安全。 我應該如何在正確的Java中執行此操作?

這本質上是不安全的。

如果將Channel<MyThing>添加到列表,然后使用OtherMethod()調用OtherMethod()發生YourThing

您應該使整個類通用(並使成員成為非靜態),並對通道和參數使用相同的T

您的方法需要一個類型參數public <T extends Something> void method(T foo)

public class Channel<T extends Something> {
  public Channel() {
  }

  public <T extends Something> void method(T foo) {
  }
}

public class Manager {
   private static ArrayList<Channel<? extends Something>> channels = new ArrayList<Channel<? extends Something>>();

   public static <T extends Something> void OtherMethod(T foo) {
     for (Channel<? extends Something> c : channels)
        c.method(foo); // this does not work
   }
}

暫無
暫無

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

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