简体   繁体   English

Java —传递通用参数

[英]Java — passing generic parameters

I am trying to write a method that takes in any subclass of MyInterface as a parameter, but getting syntax errors. 我正在尝试编写一种方法,该方法将MyInterface的任何子类都作为参数,但是出现语法错误。

public Map<String, List<T extends MyInterface>> makeMap(List<T extends MyInterface>) {

  Map<String, List<T extends MyInterface>> myMap = ...

  return myMap;

}

This syntax is not valid. 此语法无效。 The signature gives the error "misplaced construct". 签名给出错误“构造错误”。 But, the idea is that I can pass any subclass of MyInterface inn place of T. Can this be done in Java? 但是,我的想法是我可以传递MyInterface inn的任何子类代替T。这可以用Java完成吗? how? 怎么样?

You are mixing up the concepts of declaring a generic type and referring to that generic type. 您正在混淆声明泛型类型并引用该泛型类型的概念。 Assuming that you want the method to be generic, declare the generic type parameter before the return type, then refer to it plainly as T elsewhere: 假设您希望方法是泛型的,请在返回类型之前声明泛型类型参数,然后在其他地方将其简单地称为T

//      Declaration                            ref              ref
public <T extends MyInterface> Map<String, List<T>> makeMap(List<T>) {
  //              ref
  Map<String, List<T>> myMap = ...

  return myMap;

}
public <T extends MyInterface> Map<String, List<T>> makeMap(List<T> myList) {

More on generic methods here 更多关于通用方法的信息

I also noticed that in your original method declaration, you didn't have a variable defined for your method parameter. 我还注意到,在您的原始方法声明中,您没有为方法参数定义变量。

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

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