OnJava8-Examples/typeinfo/DynamicSupplier.java

44 lines
971 B
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// typeinfo/DynamicSupplier.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-12-15 11:47:04 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-12-15 11:47:04 -08:00
import java.util.function.*;
import java.util.stream.*;
class CountedInteger {
private static long counter;
private final long id = counter++;
@Override
public String toString() { return Long.toString(id); }
}
public class DynamicSupplier<T> implements Supplier<T> {
private Class<T> type;
public DynamicSupplier(Class<T> type) {
this.type = type;
}
public T get() {
try {
return type.newInstance();
} catch(InstantiationException |
IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Stream.generate(
new DynamicSupplier<>(CountedInteger.class))
.skip(10)
.limit(5)
.forEach(System.out::println);
}
}
/* Output:
10
11
12
13
14
*/