OnJava8-Examples/containers/SpringDetector.java

32 lines
1.3 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: containers/SpringDetector.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// What will the weather be?
import java.lang.reflect.*;
import java.util.*;
import static net.mindview.util.Print.*;
public class SpringDetector {
// Uses a Groundhog or class derived from Groundhog:
public static <T extends Groundhog>
void detectSpring(Class<T> type) throws Exception {
Constructor<T> ghog = type.getConstructor(int.class);
2015-05-05 11:20:13 -07:00
Map<Groundhog,Prediction> map = new HashMap<>();
2015-04-20 15:36:01 -07:00
for(int i = 0; i < 10; i++)
map.put(ghog.newInstance(i), new Prediction());
print("map = " + map);
Groundhog gh = ghog.newInstance(3);
print("Looking up prediction for " + gh);
if(map.containsKey(gh))
print(map.get(gh));
else
print("Key not found: " + gh);
}
public static void main(String[] args) throws Exception {
detectSpring(Groundhog.class);
}
} /* Output:
2015-05-05 11:20:13 -07:00
map = {Groundhog #0=Six more weeks of Winter!, Groundhog #4=Six more weeks of Winter!, Groundhog #3=Early Spring!, Groundhog #8=Six more weeks of Winter!, Groundhog #2=Early Spring!, Groundhog #5=Early Spring!, Groundhog #9=Six more weeks of Winter!, Groundhog #7=Early Spring!, Groundhog #1=Six more weeks of Winter!, Groundhog #6=Early Spring!}
2015-04-20 15:36:01 -07:00
Looking up prediction for Groundhog #3
Key not found: Groundhog #3
*///:~