使用泛型解决需要动态返回类型的问题

来源:互联网 发布:荣耀机顶盒直播软件 编辑:程序博客网 时间:2024/06/05 20:52
下午的工厂模式需要解决一个问题,需要根据传入的类型返回相应的数据类型的对象,因为之前的方案需要返回Object这个万能对象,但是弊端就是在使用工厂模式的时候,进行向下转型,为了规避这个问题,可以使用泛型,来解决动态返回类型的问题,代码如下:

public static<T> T getService(Class<T> clazz,String serviceName){
try {
return(T)ServiceFactory.class.forName(properties.getProperty(serviceName)).newInstance();
} catch (Exception e) {
//deal exception
System.out.println("Factory error!!!\n"+e.getMessage());
}
return null;
}