Java针对泛型创建对象的中存在擦除的弥补方案
在java中不能像才c++那样,直接声明泛型对象即使 T t=new T(); 但是java中针对这种问题也有一些解决方案,在这里提供三种方案
-
-
-
-
-
-
- public class CreatingTypesSolutions {
- public static void main(String[] args) {
-
- ClassAsFactory<Employ> caf1 = new ClassAsFactory<Employ>(Employ.class);
-
-
-
-
-
-
-
- ClassAsFactory2<Employ> caf21 = new ClassAsFactory2<Employ>(new EmployFactory());
- ClassAsFactory2<Integer> caf22 = new ClassAsFactory2<Integer>(new IntegerFactory());
-
- IntegerGeneric ig1=new IntegerGeneric();
- System.out.println(ig1.create());
- }
-
- }
-
- class Employ {
- }
-
- class ClassAsFactory<T> {
- public ClassAsFactory(Class<T> t) {
- try {
- T tObj = t.newInstance();
- System.out.println(tObj.getClass().getSimpleName() + " object!");
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
-
- }
-
-
- interface FactoryI<T> {
- T create();
- }
-
- class ClassAsFactory2<T> {
- public <F extends FactoryI<T>> ClassAsFactory2(F factory) {
- System.out.println(factory.create().getClass().getSimpleName() + " create successful");
- }
- }
-
- class EmployFactory implements FactoryI<Employ> {
-
- public Employ create() {
- return new Employ();
- }
-
- }
-
- class IntegerFactory implements FactoryI<Integer> {
-
- public Integer create() {
- return new Integer(0);
- }
-
- }
-
-
- abstract class GenericWithCreate<T> {
- final T element;
-
- GenericWithCreate() {
- element = create();
- }
-
- abstract T create();
- }
-
- class IntegerGeneric extends GenericWithCreate<Integer> {
-
- @Override
- Integer create() {
- return new Integer("4");
- }
-
-
- }
|
评论暂时关闭