我想编写一个方法,就像spring的bean实例化方法一样。
context.getBean("beanobjectname", Type);
我有多个接口,将由开发人员实现,开发人员会将类名放在属性文件中,我将以字符串的形式读取类名,就像在 bean.xml 中一样。我想编写一个泛型方法来实例化实现这些接口的类的对象,只需以字符串的形式传递classname,并传递我将传递接口类型的类型。 请帮忙。
编辑1
期待以下方法的内容。但是这显示了编译错误。
public <T> T getObject(String className, Class<T> type) throw ClassNotFoundException{
Class<?> clazz = Class.forName(className);
T object = (T)clazz.newInstance();
if(clazz instanceof type){
return (type)clazz;
}
return null;
}
答案 0 :(得分:-1)
instanceof不能与在运行时动态生成的类名一起使用。您必须使用Class的isAssignableFrom()方法。
参考:What is the difference between instanceof and Class.isAssignableFrom(...)?
public Object getObject(String className, Class<?> theInterface) throws Exception{
Class<?> clazz = Class.forName(className);
if(theInterface.isAssignableFrom(clazz.getClass()))
return clazz.newInstance();
else throw new Exception("Not of same type exception");
}
希望这会有所帮助:)
您应该遵循抽象工厂设计模式。
工厂模式或工厂方法模式表示只需定义用于创建对象的接口或抽象类,但让子类决定实例化哪个类。
抽象工厂模式围绕着一个创造其他工厂的超级工厂。这家工厂也被称为工厂工厂。
请参阅:
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm
https://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm