이것은 낮은 수준의 프로세스 여야하며 현재 수준에서는 동일한 결과를 얻을 수 없다는 의미는 아니지만 많은 코드가 필요하며 시스템이 조금 복잡 할 수 있습니다. 그러나 제 제안은 다음과 같을 것입니다. (올바른 것이기를 바랍니다) 우선 누가 예외 처리를 원하는지에 대한 인터페이스를 정의합니다.
interface ExceptionHandler{
void handleException(Throwable t);
}
사용자 (API)에 대한 주석을 제공하여 해당 메소드를 표시하면 예외가 발생할 수 있습니다.
@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();
}
다음 우리는 할 수있다 예외, 이런 식으로 뭔가를 throw하는 메서드를 호출하는 시작하는 인터페이스가 필요합니다.
interface Caller{
void callMethod()throws Throwable;
}
은 당신이 나를 위해 아주 잘 작동, 알아서 실행의 흐름을 관리하고 가능한 예외 핸들러
class MethodCaller{
/*
* @param isntance: instance which implemented the Caller interface
*/
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();
}
// for(Catch cx:li){cx.targetException().getName();}
}
try {
instance.callMethod();
} catch (Throwable e) {
Class<?> ec = e.getClass();
if (li == null) {
return;
}
for (Catch cx : li) {
if (cx.targetException().equals(ec)) {
ExceptionHandler h = cx.targetCatchHandler().newInstance();
h.handleException(e);
break;
}
}
}
}
}
를 호출하고 마지막으로 몇 가지 예를 할 수있는 사람이 필요합니다 춥다. 예외 처리기입니다.
public class Bar implements ExceptionHandler{//the class who handles the exception
@Override
public void handleException(Throwable t) {
System.out.println("Ta Ta");
System.out.println(t.getMessage());
}
}
및 메소드 호출자.
class Foo implements Caller{//the class who calls the method
@Override
@CatchGroup(catchers={
@Catch(targetCatchHandler=Bar.class,targetException=ArithmeticException.class),
@Catch(targetCatchHandler=Bar.class,targetException=NullPointerException.class)})
public void callMethod()throws Throwable {
int a=0,b=10;
System.out.println(b/a);
}
public static void main(String[] args) throws Exception {
Foo foo=new Foo();
MethodCaller.callMethod(foo);
}
}
하면, 사용자가 callmethod()
방법으로 메소드를 호출하는 참조로, 당신은 또한 Caller
인터페이스를 생략하고, 여분의 무리를 필요로하는 클래스에 하나 이상의 방법을 선언하는 주석을 사용 codez. 나는 약간의 손을 댈 수 있었으면 좋겠다.
주석은 독자적으로 동작을 추가하지 않습니다. 그것들은 메타 데이터입니다. 해당 동작을 발견하면 추가 할 수있는 파서를 제공해야합니다. –
나는 그것을 사소한 muckery라고 부를 것이다. AOP 또는 일부 바이트 코드 조작으로 쉽게 처리 할 수 있습니다. –