0
我在我的代碼中使用了反射,爲用戶提供了直接調用方法的機會,而無需編寫if ... else語句或開關的語調,但我遇到了問題。 我有一個名爲Exit()的方法,我想拋出自定義的異常,但是當我爲method.invoke()行添加catch語句時,編譯器告訴我那種異常從未在該語句中拋出,但用戶可能會調用該方法是絕對有可能的,我如何才能找到解決此問題的解決方案?如何使用反射指定異常類型?
這裏是我的反射代碼
try {
methodName = input.nextLine();
Class<?> facade = StoreFacade.getInstance().getClass();
Method method = facade.getDeclaredMethod(methodName);
method.setAccessible(true);
method.invoke(StoreFacade.getInstance());
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}catch (Exceptions.EndOfSessionException e){
System.out.println(e.getMessage());
}
非常感謝你 – Carmine 2014-09-20 22:30:31