0

次の問題があります。

私は基本的に他のメソッドを呼び出すメソッド「コール」を持つ抽象クラスを持っています。

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();
        }
    }
}

これで、null パラメーターを取る可能性のあるオーバーライドされたメソッド呼び出しを使用して、このクラスのサブクラスができました。基本的にそのような状況が発生した場合、スーパークラスからメソッドを呼び出したいのですが、上記の例外がスローされないため、再試行されず、メソッドは別の場所で失敗して終了します。手動でスローしてさらにパスする方法、またはそれを修正する他の方法はありますか? ご協力ありがとうございました!

@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代わりに (子) メソッドをオーバーライドします。

@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、オーバーライドされないようになっています。
  • callMethod同じパッケージからのみオーバーライド可能で呼び出し可能にprotectedしています-パブリックAPIから取り出します。

更新:@Fildorが提供するポイントを取り入れました。

于 2013-01-09T13:35:08.133 に答える