2015-12-15 11:47:04 -08:00
|
|
|
// collectionsindepth/SpringDetector.java
|
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// What will the weather be?
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
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);
|
|
|
|
Map<Groundhog,Prediction> map = new HashMap<>();
|
|
|
|
for(int i = 0; i < 10; i++)
|
|
|
|
map.put(ghog.newInstance(i), new Prediction());
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("map = " + map);
|
2015-06-15 17:47:35 -07:00
|
|
|
Groundhog gh = ghog.newInstance(3);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Looking up prediction for " + gh);
|
2015-06-15 17:47:35 -07:00
|
|
|
if(map.containsKey(gh))
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(map.get(gh));
|
2015-06-15 17:47:35 -07:00
|
|
|
else
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("Key not found: " + gh);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
2015-06-15 17:47:35 -07:00
|
|
|
detectSpring(Groundhog.class);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-12-15 11:47:04 -08:00
|
|
|
map = {Groundhog #2=Early Spring!, Groundhog #3=Early
|
|
|
|
Spring!, Groundhog #1=Six more weeks of Winter!, Groundhog
|
|
|
|
#8=Six more weeks of Winter!, Groundhog #9=Six more weeks
|
|
|
|
of Winter!, Groundhog #6=Early Spring!, Groundhog #5=Early
|
|
|
|
Spring!, Groundhog #0=Six more weeks of Winter!, Groundhog
|
|
|
|
#7=Early Spring!, Groundhog #4=Six more weeks of Winter!}
|
2015-06-15 17:47:35 -07:00
|
|
|
Looking up prediction for Groundhog #3
|
|
|
|
Key not found: Groundhog #3
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|