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