我有一个由少数类实现的接口。基于类的全名我想初始化类对象。
接口,
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"
的
如何根据名称初始化类。
答案 0 :(得分:6)
你几乎就在那里:
instance = (InterfaceSample) Class.forName(className).newInstance();
记得用以下方法标记方法:
throws Exception
因为newInstance()
也被标记(确切地说InstantiationException
和IllegalAccessException
)。
答案 1 :(得分: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;
}
}