Java – how to create a generic type safe HashMap by class type?
See English answers > java map with values limited by key's type parameter5
Later, I want to pass the class type and get a reference to that particular object Simple example:
Map<Class<?>,?> values = new HashMap<>(); public <T> t get(Class<T> type) { return values.get(type); } //pet and car do not share any interface or parent class class Pet; class Car; //error: not applicable for arguments values.put(Pet.class,new Pet()); values.put(Car.class,new Car());
Usage:
values.get(Pet.class);
How to create such a general hash diagram and lookup function accordingly?
Solution
You need to store certain types of objects. If you want to place any other objects in the map, start from here:
Map<Class<?>,Object> values = new HashMap<>();
This must be done because? It is not a specific object, but for the type of map storage, the object is
So the following code snippet works without any warnings:
Map<Class<?>,Object> values = new HashMap<>(); values.put(Pet.class,new Car());
The trick now is to get the object. We do it as follows:
@SuppressWarnings("unchecked") private <T> T get(Class<T> clazz) { return (T)values.get(clazz); }
Now, your goal is to ensure that the mapping contains pairs that do not appear wrong at run time If you use car Class add a new car () instance, then you will encounter an error
So the following example code:
values = new HashMap<>(); values.put(Pet.class,new Pet()); values.put(Car.class,new Car()); System.out.println("get(Pet.class).getClass() = " + get(Pet.class).getClass()); System.out.println("get(Car.class).getClass() = " + get(Car.class).getClass());
Will print:
get(Pet.class).getClass() = class testproject8.Pet get(Car.class).getClass() = class testproject8.Car