我想声明的是包含将返回实现双方的事情列表的方法的接口Comparator<Object>和Action,即
<T extends Comparator<Object> & Action> List<T> getThings();
Run Code Online (Sandbox Code Playgroud)
编译很好,但是当我尝试调用这个方法时会出现问题.我希望能够这样做:
List<Action> things = getThings();
List<Comparator<Object>> things = getThings();
Run Code Online (Sandbox Code Playgroud)
当我尝试这样做时,我得到以下编译错误:
incompatible types; no instance(s) of type variable(s) T exist so that
java.util.List<T> conforms to java.util.List<javax.swing.Action>
found : <T>java.util.List<T>
required: java.util.List<javax.swing.Action>
Run Code Online (Sandbox Code Playgroud)
以下内容也不起作用:
List<? extends Action> things = getThings();
List<? extends Comparator<Object>> things = getThings();
Run Code Online (Sandbox Code Playgroud)
达到这种效果的另一种方法是创建一个扩展两个空的接口Comparator<Object>和Action并使用它作为返回类型,即
public interface ComparatorAction extends Comparator<Object>, Action { }
List<ComparatorAction> getThings();
Run Code Online (Sandbox Code Playgroud)
但我不想这样做.必须有办法做我想做的事,对吧?有任何想法吗?
谢谢!
PS我很难为这篇文章争取一个好头衔,所以随时可以改变它.
您还可以参数化您调用的方法getThings()。例如:
public static <U extends Comparator<Object> & Action> void main(String[] args) {
List<U> l = getThings();
Action a = l.get(0);
Comparator<Object> c = l.get(0);
}
Run Code Online (Sandbox Code Playgroud)