How to define an interface throwing a generic exception type?
题
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.
不隶属于 StackOverflow