java 一个通用的Generator——批量创建类

    下 面的程序可以为任何类构造一个Generator,只要该类具有默认的构造函数。为了减少类型声明,他提供了一个泛型方法,用以生成BasicGenerator:

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 (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static <T> Generator<T> create(Class<T> type) {
        return new BasicGenerator<T>(type);
    }
    
    
    
    public static void main(String[] args) {
        Generator<CountedObject> gen = BasicGenerator.create(CountedObject.class);
        for (int i = 0; i < 5; i++) {
            System.out.println(gen.next());
        }
    }
}

    这个类提供了一个基本实现,用以生成某个类的对象。这个类必须具备两个特点:(1)它必须声明为public。(因为BasicGenerator与要处理的类在不同的包中,所以该类必须声明为public,并且不只是具有包内访问权限。)(2)它必须具备默认的构造函数(无参构造函数)。    

    为了测试上面的BasicGenerator,我们需要创建一个类:

class CountedObject {
    private static long counter = 0;
    private final long id = counter++;// 用于记录创建对象的次数
    public long getId() {
        return id;
    }
    public String toString() {
        return "CountedObject" + id;
    }
}

输出结果:

CountedObject0
CountedObject1
CountedObject2
CountedObject3
CountedObject4



猜你喜欢

转载自blog.csdn.net/u013276277/article/details/80804418