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 (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> Generator<T> create(Class<T> type) {
return new BasicGenerator<T>(type);
}
}
public class CountedObject {
public static long count = 0;
private final long id = count++;
public long id() {
return id;
}
public String toString() {
return "CountedObject_" + id;
}
}
public class BasicGeneratorDemo {
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());
}
}
Output:
CountedObject_0
CountedObject_1
CountedObject_2
CountedObject_3
CountedObject_4