java针对泛型创建对象的中存在擦除的弥补方案

在java中不能像才c++那样,直接声明泛型对象即使 T t=new T(); 但是java中针对这种问题也有一些解决方案,在这里提供三种方案

/**
 * 
 * although in c++ could use new T() to creating a instance of type, but java not support this approach, this class
 * provider 3 solutions for this situation
 * @version $Revision: $ $Name: $
 */
public class CreatingTypesSolutions {
    public static void main(String[] args) {
        // solution 1: pass in a factory object, and use that to make the new instance
        ClassAsFactory<Employ> caf1 = new ClassAsFactory<Employ>(Employ.class);
        /*
         * This compiles, but fails with ClassAsFactory<Integer> because Integer has no default constructor. Because the
         * error is not caught at compile time, this approach is frowned upon by the Sun folks. They suggest instead
         * that you use solution2
         */
        // ClassAsFactory<Integer> caf2 = new ClassAsFactory<Integer>(Integer.class);
        // solution 2:
        ClassAsFactory2<Employ> caf21 = new ClassAsFactory2<Employ>(new EmployFactory());
        ClassAsFactory2<Integer> caf22 = new ClassAsFactory2<Integer>(new IntegerFactory());
        // solution 3: Template Method design pattern
        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();
        }
    }

}

// solution 2 :intgerface
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);
    }

}

// solution 3: Template Method design pattern
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");
    }
    

}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值