OnJava8-Examples/reflection/DynamicSupplier.java

46 lines
1.0 KiB
Java
Raw Normal View History

// reflection/DynamicSupplier.java
// (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.*;
class ID {
2015-12-15 11:47:04 -08:00
private static long counter;
private final long id = counter++;
@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;
}
@Override public T get() {
2015-12-15 11:47:04 -08:00
try {
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(
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
*/