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

I am looking at a heterogeneous container template from Bloch Effective Java, and I'm trying to determine why a class reference is required when inserting objects into a heterogeneous container. Can't I use instance.getClass() to get this link? Is this not a JPA entity manager 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); } 
+6
source share
2 answers

No, you cannot do this because it will not give you a class of a reference type in case of inheritance, but rather a class of the actual type of the object.

Consider the following example:

 Number num = new Integer(4); System.out.println(num.getClass()); 

this will print:

 class java.lang.Integer 

not java.lang.Number .

+5
source

I really need a different approach (with .getClass ()), so I assume that both implementations may be useful.

 class Favorites { private Map<Class<?>, Object> favorites = new HashMap<>(); public <T> void putFavorite(Class<T> type, T instance) { favorites.put(Objects.requireNonNull(type), instance); } public <T> void putFavorite(T instance) { favorites.put(instance.getClass(), instance); } public <T> T getFavorite(Class<T> type) { return type.cast(favorites.get(type)); } public static void main(String[] args) { Favorites favorites = new Favorites(); Number num = new Integer(4); favorites.putFavorite(Number.class, num); //ADDS Number -> 4 //favorites.putFavorite(Integer.class, num); //Error: no suitable method found for putFavorite(java.lang.Class<java.lang.Integer>,java.lang.Number) favorites.putFavorite(num); //ADDS Integer -> 4 System.out.println(favorites.favorites); //{class java.lang.Integer=4, class java.lang.Number=4} } } 
0
source

Source: https://habr.com/ru/post/951238/


All Articles