2012-03-06 76 views
0

我正在從書中做一些練習,並在以下練習中遇到一些問題。使用構造函數創建基於參數化超類的生成器

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()方法。我怎樣才能做到這一點?

謝謝

+0

您可以加入BasicGeneratorDemo並告訴我們在哪兒你就完蛋了? – 2012-03-06 10:16:31

+0

對不起復制錯誤的類。現在很好,評論指向我卡住的地方。 – aretai 2012-03-06 10:20:54

回答

1

OK,你需要傳遞一個參數:

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

很接近謝謝 – aretai 2012-03-06 10:30:45

相關問題