2016-03-02 68 views
0

我有一個由少數類實現的接口。基於類的全名我想初始化類對象。如何從類類型轉換爲接口

接口,

public interface InterfaceSample{ 
} 

類文件,

public class ABC implements InterfaceSample{ 
} 
public class XYZ implements InterfaceSample{ 
} 

樣本測試類,

public class SampleManager{ 
public static InterfaceSample getInstance(String className) { 
    InterfaceSample instance = null; 
    try { 
     instance = (InterfaceSample) Class.forName(className); 
    } catch (ClassNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return instance; 
} 

} 

我收到以下錯誤,

"Cannot cast from Class<capture#1-of ?> to InterfaceSample" 

我怎麼能初始化基於其名稱的類。

+1

你期望'Class.forName(...)'返回什麼? – sisyphus

+0

你真的需要在那裏演員嗎?無權利 ? –

+0

@sisyphus,類型。這是我愚蠢的錯誤。感謝您的指導。 – Kajal

回答

6

就快:

instance = (InterfaceSample) Class.forName(className).newInstance(); 

記得標記方法:

throws Exception 

因爲newInstance()被標記左右爲好(它會拋出InstantiationExceptionIllegalAccessException要準確)。

+0

感謝LeleDumbo,它的工作。 – Kajal

+0

請按照此處所述接受答案:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – LeleDumbo

2

您必須在該類上調用newInstance()以獲取實例。

public class SampleManager{ 
    public static InterfaceSample getInstance(String className) throws Exception { 
     InterfaceSample instance = null; 
     try { 
      instance = (InterfaceSample) Class.forName(className).newInstance(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
     return instance; 
    } 
} 
相關問題