Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When inserting objects into a type-safe heterogeneous container, why do we need the class reference?

Tags:

java

class

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);
}
like image 795
jdgilday Avatar asked Aug 07 '13 16:08

jdgilday


1 Answers

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.

like image 169
Rohit Jain Avatar answered Oct 02 '22 07:10

Rohit Jain