2021-03-04 16:15:04 -07:00
|
|
|
// reflection/DynamicSupplier.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 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.*;
|
|
|
|
|
2021-01-31 15:42:31 -07:00
|
|
|
class ID {
|
2015-12-15 11:47:04 -08:00
|
|
|
private static long counter;
|
|
|
|
private final long id = counter++;
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public String toString() {
|
|
|
|
return Long.toString(id);
|
|
|
|
}
|
|
|
|
// A public default constructor is required
|
|
|
|
// to call getConstructor().newInstance():
|
|
|
|
public ID() {}
|
2015-12-15 11:47:04 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
public class DynamicSupplier<T> implements Supplier<T> {
|
|
|
|
private Class<T> type;
|
|
|
|
public DynamicSupplier(Class<T> type) {
|
|
|
|
this.type = type;
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public T get() {
|
2015-12-15 11:47:04 -08:00
|
|
|
try {
|
2021-01-31 15:42:31 -07:00
|
|
|
return type.getConstructor().newInstance();
|
2020-10-07 17:06:42 -06:00
|
|
|
} catch(Exception e) {
|
2015-12-15 11:47:04 -08:00
|
|
|
throw new RuntimeException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Stream.generate(
|
2021-01-31 15:42:31 -07:00
|
|
|
new DynamicSupplier<>(ID.class))
|
2015-12-15 11:47:04 -08:00
|
|
|
.skip(10)
|
|
|
|
.limit(5)
|
|
|
|
.forEach(System.out::println);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
|
|
|
10
|
|
|
|
11
|
|
|
|
12
|
|
|
|
13
|
|
|
|
14
|
|
|
|
*/
|