1
我在我的Spring Batch項目中使用java反射來創建通用ItemProcessor
。我目前堅持如何拋出一個名字被作爲這個ItemProcessor
的參數傳遞的類的異常。反映:實例化並拋出字符串中的類名異常
在我的代碼中,我設法從String參數中獲取實際的類,然後獲取所需的構造函數(帶有1個參數)。但是當我想實例化(作爲參數傳遞的類的實例)並拋出它時,我不知道如何聲明這個異常的容器。
下面的代碼樣本中,???
在哪裏我卡:
String exceptionClass; // With getter/setter
String exceptionText; // With getter/setter
Class<?> clazz;
Constructor<?> constructor;
try {
// Get the Exception class
clazz = Class.forName(exceptionClass);
// Get the constructor of the Exception class with a String as a parameter
constructor = clazz.getConstructor(String.class);
// Instantiate the exception from the constructor, with parameters
??? exception = clazz.cast(constructor.newInstance(new Object[] { exceptionText }));
// Throw this exception
throw exception;
} finally {
}
編輯
有一件事我可能需要補充的是,我需要引發異常與作爲參數傳遞的確切類相同,因爲Spring批處理「跳躍機制」基於異常的類名。
泛型異常呢? '異常異常=(例外)clazz.cast(...)' – user902383
@ user902383如果我直接使用'Exception',拋出的異常將不會被Spring批處理捕捉到'' –
Thrax
這就是沒有足夠大的圖片。當您將其更改爲Exception時,是否有一些代碼捕獲它並將其轉換爲RuntimeException與原因?或者是這個方法和上面所有允許拋出任何異常實例?它也可以被一些代理轉換... –