gpt4 book ai didi

java - 使用构造函数创建基于参数化父类(super class)的生成器

转载 作者:行者123 更新时间:2023-12-01 15:30:27 25 4
gpt4 key购买 nike

我正在做书上的一些练习,但对以下练习有一些问题。

 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( ) 方法。我怎样才能实现这一目标?

谢谢

最佳答案

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

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

关于java - 使用构造函数创建基于参数化父类(super class)的生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9581545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com