10

我想定义一个接口,比如

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

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

谢谢

4

4 回答 4

15

您只需要将异常类型限制为适合抛出。例如:

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

也许:

interface Visitor<ArgType, ResultType, ExceptionType extends Exception> {
    ResultType visitProgram(String prog, ArgType arg) throws ExceptionType;
}
于 2012-03-19T23:02:14.870 回答
6

您的泛化参数需要扩展 Throwable。像这样的东西:

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

   public void someMethod(K k, V v) throws E {
      return;
   }
}
于 2012-03-19T23:01:50.100 回答
1

你可以做类似的事情

public interface Test<T extends Throwable> {
    void test() throws T;
}

然后,例如

public class TestClass implements Test<RuntimeException> {
    @Override
    public void test() throws RuntimeException {
    }
}

当然,当您实例化该类时,您必须声明抛出的异常。

编辑:当然,替换Throwable为任何将扩展的自定义异常ThrowableException类似异常。

于 2012-03-19T23:02:34.603 回答
-4

如果我理解这个问题,你可以抛出

Exception

因为它是父类。

于 2012-03-19T23:00:27.447 回答