如何定义抛出一般异常类型的接口?

Sky*_*sis 5 java generics interface exception throws

我想定义一个界面,比如

public interface Visitor <ArgType, ResultType, SelfDefinedException> {
     public ResultType visitProgram(Program prog, ArgType arg) throws SelfDefinedException;
     //...
}
Run Code Online (Sandbox Code Playgroud)

在实现过程中,selfDefinedException会有所不同.(selfDefinedException为现在的通用undefined)有没有办法做到这一点?

谢谢

Jon*_*eet 11

您只需要将异常类型约束为适合抛出.例如:

interface Visitor<ArgType, ResultType, ExceptionType extends Throwable> {
    ResultType visitProgram(String prog, ArgType arg) throws ExceptionType;
}
Run Code Online (Sandbox Code Playgroud)

也许:

interface Visitor<ArgType, ResultType, ExceptionType extends Exception> {
    ResultType visitProgram(String prog, ArgType arg) throws ExceptionType;
}
Run Code Online (Sandbox Code Playgroud)


Per*_*ion 5

您的通用参数需要扩展Throwable.像这样的东西:

public class Weird<K, V, E extends Throwable> {

   public void someMethod(K k, V v) throws E {
      return;
   }
}
Run Code Online (Sandbox Code Playgroud)