java泛型--创建类型实例的几种方法

因为泛型的擦除,所以任何在运行时需要知道确切类型信息的操作都将无法工作。

public class Erased<T> {
    private final int SIZE = 100;
    public static void f(Object arg){
         if(arg instanceof T){}   //错误
         T var = new T();         //错误
         T[] array = new T[SIZE]; //错误
         T[] array = (T)new Object[SIZE]; //警告
    }
}

引入类型标签,使用动态的isInstance():


class Building {}

class House extends Building {}

public class ClassTypeCapture<T> {
    Class<T> kind;
    public ClassTypeCapture(Class<T> kind) {
        this.kind = kind;
    }
    public boolean f(Object obj) {
        return kind.isInstance(obj);
    }

    public static void main(String[] args) {
        ClassTypeCapture<Building> ctt1 = new ClassTypeCapture<Building>(Building.class);
        System.out.println(ctt1.f(new Building()));
        System.out.println(ctt1.f(new House()));
    }
}

创建类型实例:
new T()无法实现,部分原因是因为擦除,而另一部分原因是因为编译器不能验证T是否具有默认构造器。
1.传递一个工厂对象,并使用它来创建新的实例。

class ClassAsFactory<T> {
    T x;
    public ClassAsFactory(Class<T> kind) {
        try {
            x = kind.newInstance();
        } catch (Exception e) {
            throw new  RuntimeException(e);
        }
    }
}

class Employee {}
public class InstantiateGenericType {
    public static void main(String[] args) {
        ClassAsFactory<Employee> fe = new ClassAsFactory<Employee>(Employee.class);
        System.out.println("ClassAsFactory<Employee> succeeded");
        try {
            ClassAsFactory<Integer> fi = new ClassAsFactory<Integer>(Integer.class);
        } catch (Exception e) {
            System.out.println("ClassAsFactory<Integer> failed");
        }
    }
}
/**
 * 因为Integer没有默认的构造函数,所以ClassAsFactory<Integer>会失败
 * 因为这个错误不是编译期捕获的,所以并不赞成使用这种方法,建议使用显式
 * 的工厂,并将其限制类型,使得只能接受实现了这个工厂的类。
 */

2.显式工厂

class Foo2<T> {
    private T x;
    //F为工厂
    public <F extends Factory<T>> Foo2(F factory) {
        x = factory.create();
    }
}
//普通类,实现工厂接口
class IntegerFactory implements Factory<Integer> {
    public Integer create() {
        return new Integer(0);
    }
}

class Widget {
    //静态内部类,实现工厂接口
    public static class Factory implements fanxing.Factory<Widget> {
        public Widget create() {
            return new Widget();
        }
    }
}
public class FactoryConstraint {
    public static void main(String[] args) {
        new Foo2<Integer>(new IntegerFactory());
        new Foo2<Widget>(new Widget.Factory());
    }
}

3.模板方法设计模式

//模板类
abstract class GenericWithCreate<T> {
    final T element;
    GenericWithCreate() {
        element = create();
    }
    //create()交由具体要实例化的子类实现
    abstract T create();
}

class X {}

class Creator extends GenericWithCreate<X> {
    X create() {
        return new X();
    }
    void f() {
        System.out.println(element.getClass().getSimpleName());
    }
}
public class CreateorGeneric {
    public static void main(String[] args) {
        Creator c = new Creator();
        c.create();
    }
}
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值