0

有以下问题:

我有一个带有方法“调用”的抽象类,该方法基本上调用了一些 otherMethod,如果 otherMethod 抛出异常,我尝试通过重新记录并再次调用“调用”方法来修复 catch。

public Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
    while (true) {
        try {
            return callMethod(methodName, parameters, parameterTypes);
        } catch (SomeException e) {
            if (numberOfTriesLeft-- == 0) {
                throw new RetryingException();
            }
            login();
        }
    }
}

现在我有一个此类的子类,它具有可能采用空参数的重写方法调用。基本上,如果发生这种情况,我想从超类调用方法,但不会抛出上面提到的异常,因此,不会重试并且方法会在其他地方失败。有没有办法手动抛出并进一步传递或任何其他方式来修复它?感谢您的帮助!

@Override
public Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
    if (parameters[0] == null){
        // What to do here if I want to throw SomeException here to end up in a catch block from the call method in the superclass? Or how to change it
    }
    // Everything ok. No null params
    ...
    return super.call(methodName, parameters, parameterTypes);
}
4

1 回答 1

1

根据我的经验,您可以做的是拥有这样的父方法:

public final Object call(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
    try {
        callMethod(methodName, parameters, parameterTypes)
    } catch (Exception ex) {
        // Handle any exception here...
    }
}

protected Object callMethod(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
    // .. your code
}

然后改写callMethod(child) 方法:

@Override
protected Object callMethod(String methodName, Object[] parameters, Class[] parameterTypes) throws RetryingException, RemoteException {
    // Exception thrown here will now be caught!
    return super.callMethod(methodName, parameters, parameterTypes);
}

因此,这将接口方法与可覆盖方法分开。我在现有的 API 中经常看到这种模式。

几点:

  • call现在正在final阻止它被覆盖。
  • callMethodprotected使其只能从同一个包中覆盖和调用 - 将其从公共 API 中取出。

更新:接受@Fildor 提供的观点。

于 2013-01-09T13:35:08.133 回答