使用构造函数创建基于参数化超类的Generator

时间:2012-03-06 10:11:32

标签: java constructor

我正在从书中做一些练习,并且在下面的练习中遇到一些问题。

 package net.mindview.util; 

public interface Generator<T> { T next(); } ///:~

    package net.mindview.util;

public class BasicGenerator1<T> implements Generator<T> {

      private Class<T> type;

      public BasicGenerator1(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);

        }

      }

      // Produce a Default generator given a type token:

      public static <T> Generator<T> create(Class<T> type) {

        return new BasicGenerator1<T>(type);

      }

    } ///:~

package cont;

public class CountedObject {

      private static long counter = 0;

      private final long id = counter++;

      public long id() { return id; }

      public String toString() { return "CountedObject " + id;}

    } ///:~

package cont;

import net.mindview.util.*;



public class BasicGeneratorDemo {

  public static void main(String[] args) {

    //this line works
    //Generator<CountedObject> gen = BasicGenerator1.create(CountedObject.class);

//am stuck here
      Generator<CountedObject> gen = new BasicGenerator1<CountedObject>;

    for(int i = 0; i < 5; i++)

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

  }

}

我必须更改BasicGeneratorDemo.java,以便它使用显式构造函数而不是通用create()方法。我怎样才能做到这一点?

谢谢

1 个答案:

答案 0 :(得分:1)

好的,你需要传递一个参数:

Generator<CountedObject> gen = new BasicGenerator1<CountedObject>(CountedObject.class);