public interface Generator<T> {
T next();
}
package generic.interfaces;
public class BasicGenerator<T> implements Generator<T> {
private Class<T> type;
public BasicGenerator(Class<T> type) {
this.type = type;
}
@Override
public T next() {
// TODO Auto-generated method stub
try {
return type.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException();
}
}
public static <T> Generator<T> create(Class<T> type) {
return new BasicGenerator<T>(type);
}
public static void main(String[] args) {
Generator<CountedObject> obj = BasicGenerator.create(CountedObject.class);
for(int i=0;i<5;i++){
System.out.println(obj.next());
//obj.next();
}
}
}
输出:
CountedObject:0
CountedObject:1
CountedObject:2
CountedObject:3
CountedObject:4