泛型讨论------一个更通用的对象生成器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; }
  public T next() {
    try {
      // Assumes type is a public class:
      return type.newInstance();
    } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  public static <T> Generator<T> create(Class<T> type) {
    return new BasicGenerator<T>(type);
  }
}

 

这个类用于生产某个类的对象,这个类必须具备俩个特征。

1,它必须声明为public类型。

2。它必须具备默认无惨构造函数。

 

使用例子

 

public static void main(String[] args){

	Generator<String> gen = BasicGenerator.create(String.class);
	for(int i=0;i<10;i++){

		System.out.println(gen.next());
	}
}

 

可以看到,使用泛型方法创建Generator对象,大大减少了我们要编写的代码,java泛型要求传入Class 对象,以便在create方法中用它进行类型推断。

 

 

 

你可能感兴趣的:(generator)