I'm checking out the heterogeneous container pattern from Bloch's Effective Java and I'm trying to determine why the class reference is needed when inserting objects into the heterogeneous container. Can't I use instance.getClass()
to get this reference? Isn't JPA's entity manager an example of this?
interface BlochsHeterogeneousContainer {
<T> void put(Class<T> clazz, T instance);
<T> T get(Class<T> clazz);
}
interface AlternativeHeterogeneousContainer {
// Class<T> not needed because we can use instance.getClass()
<T> void put(T instance);
<T> T get(Class<T> clazz);
}
No you can't do that, as it won't give you class of reference type in case of inheritance, rather the class of actual object type.
Consider this example:
Number num = new Integer(4);
System.out.println(num.getClass());
this will print:
class java.lang.Integer
and not java.lang.Number
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With