因为泛型的擦除,所以任何在运行时需要知道确切类型信息的操作都将无法工作。
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();
}
}