
1、说明
泛型代码中不能new T()的原因有两个,一是因为擦除,不能确定类型;而是无法确定T是否包含无参构造函数。
我们通过工厂模式+泛型方法制作实例对象,制作IntegerFactory工厂,制作Integer实例,如果后来代码发生变化,可以追加新的工厂类型。
2、实例
/**
*使用工厂方法来创建实例
*
*@param<T>
*/
interfaceFactory<T>{
Tcreate();
}
classCreater<T>{
Tinstance;
public<FextendsFactory<T>>TnewInstance(Ff){
instance=f.create();
returninstance;
}
}
classIntegerFactoryimplementsFactory<Integer>{
@Override
publicIntegercreate(){
Integerinteger=newInteger(9);
returninteger;
}
}
以上就是Java创建类型实例的方法,希望对大家有所帮助。更多Java学习指路:Java基础
原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END

















































暂无评论内容