It should be a low-level process, and this does not mean that we cannot have the same with the current level, but it may need a bunch of code and a little compromise the system. However, my suggestion will be like this (I hope I understood correctly), first define an interface for those who want to handle exceptions, something like this.
interface ExceptionHandler{ void handleException(Throwable t); }
then provide annotation for the user (API) to mark his methods, may cause some exceptions.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) @interface Catch{ public Class<? extends ExceptionHandler> targetCatchHandler(); public Class<? extends Throwable> targetException() default Exception.class; } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface CatchGroup{ public Catch[] catchers(); }
Next, we need an interface to start calling a method that may throw an exception, something like this.
interface Caller{ void callMethod()throws Throwable; }
then you need a guy who cares and manages the thread of execution and calls a possible exception handler
class MethodCaller{ public static void callMethod(Caller instance) throws Exception { Method m = instance.getClass().getMethod("callMethod"); Annotation as[] = m.getAnnotations(); Catch[] li = null; for (Annotation a : as) { if (a.annotationType().equals(CatchGroup.class)) { li = ((CatchGroup) a).catchers(); }
and finally, let's have an example, it works very well for me, that's cool. exception handler.
public class Bar implements ExceptionHandler{
and the calling method.
class Foo implements Caller{
as you see, the user must call methods with the callmethod() method, you also omit the Caller interface and use the annotation to declare more than one method in the class that it needs a bunch of additional codez. I hope I could do a little work.
user2511414
source share