-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicgenrator.java
More file actions
40 lines (33 loc) · 957 Bytes
/
Copy pathBasicgenrator.java
File metadata and controls
40 lines (33 loc) · 957 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package GenericInterface;
public class Basicgenrator<T> implements Generator<T> {
private Class<T> type;
public Basicgenrator(Class<T> type) {
this.type = type;
}
@Override
public T next() {
try {
// type对应的类必须有默认构造器,因为newInstance调用的是默认构造器
return type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> Generator<T> create(Class<T> type) {
return new Basicgenrator<>(type);
}
public static void main(String[] args) {
Generator<CounterObejct> gen = Basicgenrator.create(CounterObejct.class);
for (int i = 0; i < 2; i++) {
System.out.println(gen.next());
}
}
}
//测试类
class CounterObejct{
private static long counter=0;
@Override
public String toString() {
return " " + counter;
}
}