문제

I wanna define an interface, like

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

during implementation, selfDefinedException varies. (selfDefinedException as a generic undefined for now) Is there a way to do this?

Thanks

도움이 되었습니까?

해결책

You just need to constrain the exception type to be suitable to be thrown. For example:

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

Or perhaps:

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

다른 팁

Your genericized parameter would need to extend Throwable. Something like this:

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

   public void someMethod(K k, V v) throws E {
      return;
   }
}

You can do something like

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

And then, for example

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

Of course, when you instantiate the class you have to declare the exception that is thrown.

EDIT: Of course, replace Throwable with any of your self defined exceptions that will extend Throwable, Exception or similar.

If I understand the question, you can throw

Exception

as it is the parent class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top