2015-10-20 18 views
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批處理「跳躍機制」基於異常的類名。

+0

泛型異常呢? '異常異常=(例外)clazz.cast(...)' – user902383

+0

@ user902383如果我直接使用'Exception',拋出的異常將不會被Spring批處理捕捉到'' – Thrax

+0

這就是沒有足夠大的圖片。當您將其更改爲Exception時,是否有一些代碼捕獲它並將其轉換爲RuntimeException與原因?或者是這個方法和上面所有允許拋出任何異常實例?它也可以被一些代理轉換... –

回答

1

我發現了一個工作解決方案,明確規定Class對象擴展爲Exception。然後我可以拋出它而不需要聲明這個類的新對象。

// Get class of the exception (with explicit "extends Exception") 
Class<? extends Exception>clazz = (Class<? extends Exception>) Class.forName(exceptionClass); 

// Get the constructor of the Exception class with a String as a parameter 
Constructor<?> constructor = clazz.getConstructor(String.class); 

// Instantiate and throw immediatly the new Exception 
throw clazz.cast(constructor.newInstance(new Object[] { exceptionText })); 
相關問題