I've used Joshua Bloch's heterogeneous container idea to type safely store/retrieve values. But I also am storing primitive types (which in the container are auto boxed to Object types), and am unable to retrieve the values as primitive types. The type.cast(value) appears to auto box the value back to an object (I had already converted to a double) at which point it cannot type cast back to a primitive.
Here is my code:
import java.util.LinkedHashMap;
public class TestHeterogeneous {
static private LinkedHashMap<Class<?>, Object> elements = new LinkedHashMap<>();
static public <T> void putElement(Class<T> type, T value) {
elements.put(type, value);
}
static public <T> T getElement(Class<T> type) {
double dValue = (double) elements.get(type);
return type.cast(dValue);
}
public static void main(String[] args) {
putElement(double.class, 12.345);
System.out.println("double value: "+getElement(double.class));
}
}
Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Double to double
at java.lang.Class.cast(Class.java:3084)
at tooldevelopment.TestHeterogeneous.getElement(TestHeterogeneous.java:14)
Thanks, I appreciate your help.