使用带有 List 作为方法参数的 java 泛型的编译器错误并抛出泛型异常

Compiler error using java generics with a List as a method parameter and throws generic Exception

我在项目中使用泛型时遇到编译器错误。我生成一个示例代码:

我的 Bean 接口

package sample;

public interface MyBeanInterface {
  Long getId();
  String getName();
}

我豆混凝土Class

package sample;

public class MyBean implements MyBeanInterface {
    private Long id;
    private String name;

    @Override
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

我的管理界面

package sample;

import java.util.List;

public interface MyManagerInterface<T extends MyBeanInterface> {

    <EXCEPTION extends Exception> List<T> sortAll(List<T> array) throws EXCEPTION;

    List<T> sortAll2(List<T> array);

    <EXCEPTION extends Exception> List<T> sortAll3() throws EXCEPTION;

}

我的经理具体 Class

package sample;

import java.io.IOException;
import java.util.List;

public class MyConcreteManager implements MyManagerInterface<MyBean> {

   @Override
   //this fails
   public List<MyBean> sortAll(List<MyBean> array) throws IOException {
       return null;
      }

    @Override
   //this works
    public List<MyBean> sortAll2(List<MyBean> array) {
        return null;
    }

    @Override
   //this works
    public List<MyBean> sortAll3() {
        return null;
    }

}

我尝试在接口中使用没有方法参数 (sortAll()) 的方法 sortAll 并且它编译,仅使用接口中的异常也可以,但同时使用两者都不行。

谢谢。

关于sortAll(List<T> list)方法,你必须做:

@Override
public <E extends Exception> List<T> sortAll(List<T> array) throws E {
    // TODO Auto-generated method stub
    return null;
}

然后,在调用方法时显式设置方法类型参数:

try {
    new MyConcreteManager().<IOException>sortAll(...);
} catch (IOException e) {

}

sortAll3() 实现编译得很好,因为在 Java 中,当一个方法定义覆盖另一个方法定义时,不允许抛出额外的检查异常,但它可能抛出更少。