すべてが同じ特性を共有する多くの型指定された例外があります。それらは常にゼロ以外のステータス (int) フィールドを保持します。コードは通常、ステータス変数をチェックし、それがゼロでない場合は、対応する例外をスローします (コンテキストによって異なります)。すなわち:
if (status != 0) throw new AStatusException(status);
... // other context
if (status != 0) throw new BStatusException(status);
... // other context
if (status != 0) throw new CStatusException(status);
throwIfNotZero
ほとんどの好奇心から、この共通機能を基本クラスの静的メソッドに実装しStatusException
、さまざまなA, B, CStatusException
クラスがすべてそのクラスを継承するようにしようと考えました。これにより、うまくいけば、次のようなコードを書くことができます。
AStatusException.throwIfNonZero(status);
... // other context
BStatusException.throwIfNonZero(status);
... // other context
CStatusException.throwIfNonZero(status);
悲しいことに、私が得た最も近いものは、投稿の最後に追加したコードですが、これはあまり満足のいくものではありません。おそらくリフレクションを使用せずに、および/または冗長に見えるクラスインスタンスを渡す必要を回避するより良い方法はありますか(「使用法」を参照)?
基本例外
import java.lang.reflect.InvocationTargetException;
public class StatusException extends Exception {
public int status;
public StatusException (int status) {
this.status = status;
}
public static <T extends StatusException> void raiseIfNotZero(Class<T> klass, int code) throws T{
try {
if (code != 0) throw klass.getConstructor(Integer.TYPE).newInstance(code);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
利用方法:
AStatusException.raiseIfNotZero(AStatusException.class, status);
BStatusException.raiseIfNotZero(BStatusException.class, status);