- 使用类型标签(Java内建的工厂对象)创建泛型实例
package chapter15._8._1;
/**
* 这种方式实例化泛型成员变量并不被官方推荐,
* 因为无法确定T有默认无参构造方法。
* @param <T>
*/
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) {
// Integer没有无参构造函数
System.out.println("ClassAsFactory<Integer> failed.");
}
}
}
package chapter15._8._1;
interface FactoryI<T> {
T create();
}
class Foo2<T> {
private T x;
public <F extends FactoryI<T>> Foo2(F factory) {
x = factory.create();
}
}
/**
* 相较于Class是Java中的内建工厂对象,通过创建显示的工厂对象,
* 获得编译期检查。
*/
class IntegerFactory implements FactoryI<Integer> {
@Override
public Integer create() {
return new Integer(0);
}
}
class Widget {
public static class Factory implements FactoryI<Widget> {
@Override
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());
}
}
package chapter15._8._1;
/**
* 使用模板方法模式实例化泛型成员变量;
* @param <T>
*/
abstract class GenericWithCreate<T> {
final T element;
GenericWithCreate() {
element = create();
}
abstract T create();
}
class X {}
class Creator extends GenericWithCreate<X> {
@Override
X create() {
return new X();
}
void f() {
System.out.println(element.getClass().getSimpleName());
}
}
public class CreatorGeneric {
public static void main(String[] args) {
Creator c = new Creator();
c.f();
}
}