Java泛型 通用Generator

public interface Generator<T> {
	// 使用泛型参数
	T next();
}
public class BasicGenerator<T> implements Generator<T> {

	private Class<T> type;
	// 定义构造方法传递参数
	public BasicGenerator(Class<T> type) {
		this.type = type;
	}

	@Override
	public T next() {
		try {
			// 使用反射来创建实例
			return type.newInstance();
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	// 设计这个方法的好处是什么?
	public static <T> Generator<T> create(Class<T> type) {
		return new BasicGenerator<T>(type);
	}

}

猜你喜欢

转载自blog-chen-lian.iteye.com/blog/2359512
今日推荐