下面是我想要實作的偽代碼,大部分是完整/可用的 java。
拋出例外,我想根據已知例外型別串列檢查它,而不必進行一系列 if 檢查來查看它是否是每個型別的實體
//pretend this is the exception that was thrown
Exception e = new CustomException2();
//I want to have a set of expected types
Set<Type> expectedExceptionTypes = new HashSet<>(Arrays.asList(CustomException1, CustomException2, CustomException3));
//I want to see which type the exception matches to or else give a default (UnknownException)
Optional<Type> type = expectedExceptionTypes.stream().filter((t) -> e instanceof t).findFirst().orElse(UnknownException);
//... perform some action based on the exception type
我怎樣才能真正實作這樣的事情?我在正確的軌道上嗎?
我試圖避免的事情:
if(e instanceof CustomException1)
...
if(e instanceof CustomException2)
...
if(e instanceof CustomException3)
...
.
.
.
uj5u.com熱心網友回復:
有一種模式叫做Chain of Responsibility可以用來實作你想要的。它可以有不同的形式,你在正確的軌道上。您需要更改expectedExceptionTypes以保存您要檢查的條件以及處理它的代碼。例如,定義一個將這兩者打包在一起的類:
class ExceptionHandler {
Predicate<Exception> condition;
Consumer<Exception> handlingCode;
public ExceptionHandler(Predicate<Exception> condition, Consumer<Exception> handlingCode) {
this.condition = condition;
this.handlingCode = handlingCode;
}
}
然后只是找到滿足條件的第一個處理程式,并呼叫它:
final Set<ExceptionHandler> handlers = new HashSet<>(
Arrays.asList(
new ExceptionHandler(
v -> v instanceof CustomException1,
t -> System.out.println("Handling exception of type: " t)
),
new ExceptionHandler(
v -> v instanceof CustomException2,
t -> System.out.println("Handling exception of type: " t
)))
);
handlers.stream().filter((ExceptionHandler t) -> t.condition.test(e))
.findFirst()
.ifPresent(exceptionHandler -> exceptionHandler.handlingCode.accept(e));
注意我明確使用instanceof行內,以避免型別擦除問題,但可以使用任何有效的方法。
uj5u.com熱心網友回復:
將類存盤在 Set 中并使用contains(e.getClass()).
定義你的目標類(可能是static final常量):
Set<Class<?>> exceptionClasses = Set.of(CustomException1.class, CustomException2.class, CustomException3class); // since Java 9
然后給出
Exception e = someException;
e = exceptionClasses.contains(e.getClass()) ? e : new UnknownException();
uj5u.com熱心網友回復:
您可以通過使用Class而不是Type和比較Objects.equals(t.getCanonicalName(), e.getClass().getCanonicalName())(或下面的解釋)來修改您的代碼e.getClass().isAssignableFrom(t):
Exception e = new CustomException2();
Set<Class> expectedExceptionTypes = new HashSet<>(Arrays
.asList(CustomException1.class, CustomException2.class, , CustomException3.class));
// get type the exception matches to or else have a default UnknownException.class
Class type = expectedExceptionTypes
.stream()
.filter( t -> Objects.equals(t.getCanonicalName(), e.getClass().getCanonicalName()))
.findFirst()
.orElse(UnknownException.class);
//... perform some action based on the exception type
如果您不想“完全匹配”,請使用e.getClass().isAssignableFrom(t)代替 (有關更多資訊檢查型別別(.class)是否等于其他型別別)Objects.equals(t.getCanonicalName(), e.getClass().getCanonicalName())
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/422250.html
標籤:
下一篇:C 客戶端套接字發送原始檔案和檔案大小,Java客戶端總是多得到8個位元組。即使強制限制為-8位元組檔案也不可讀
