java利用泛型时,如何创建类型实例?

Java的解决方法是传递一个工厂对象,并使用它来创建新的实例。

1.最便捷的工厂对象就是Class对象

用Class对象的话,就可以利用newInstance()创建这个类型的新对象。

class ClassFactory<T>{
	T x;
	public ClassFactory(Class<T> kind) {
		// TODO Auto-generated constructor stub
		try {
			x = kind.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class Employee{}

public class Xian{
	public static void main(String[] args) {
		ClassFactory<Employee> fe = new ClassFactory<Employee>(Employee.class);
		System.out.println("succeed");
	}
}

这种方式并不推荐,只是可以实现。因为newInstance()的使用条件是必须要有默认的构造函数,当函数加上下面一行之后,就会在运行的时候报错(这种错误在编译的时候不会被捕捉到的)。

class ClassFactory<T>{
	T x;
	public ClassFactory(Class<T> kind) {
		// TODO Auto-generated constructor stub
		try {
			x = kind.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

class Employee{}

public class Xian{
	public static void main(String[] args) {
		ClassFactory<Employee> fe = new ClassFactory<Employee>(Employee.class);
		System.out.println("succeed");
		ClassFactory<Integer> fe2 = new ClassFactory<Integer>(Integer.class);
	}
}

2.建议使用的是显式的工厂

interface FactoryI<T>{
	T create();
}
class Foo2<T> {
	private T x;
	public <F extends FactoryI<T>>Foo2(F factory) {
		x = factory.create();
	}
}
class IntergeFactory implements FactoryI<Integer>{
	@Override
	public Integer create() {
		return new Integer(0);
	}
}
class Widght{
	public static class Factory  implements FactoryI<Widght> {
		public Widght create() {
			return new Widght();
		}
	}
}

public class Factory {
	public static void main(String[] args) {
		new Foo2<Integer>(new IntergeFactory());
		new Foo2<Widght>(new Widght.Factory());
	}
}

显式的实现方式也是有两种,第一种是类直接继承接口,第二种是在用静态内部类继承接口。

3.除此之外,还可以利用模板方法设计模式

abstract class GenericCrearte<T>{
	final T element;
	public GenericCrearte() {
		element = create();
	}
	abstract T create();
}

class App{}
class Creator extends GenericCrearte<App>{
	App create(){
		return new App();
	}
	void f(){
		System.out.println(element.getClass().getSimpleName());
	}
}

public class Factory {
	public static void main(String[] args) {
		Creator c = new Creator();
		c.f();
	}
}

其中get() 是模板方法,而Create() 实在子类中定义的,用来产生子类类型的对象。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值