I have a Map<Class,Object> .
In a method I transfer object. The method should compare the object with the classes from the Map and return the corresponding Object .
For example, in Map there are such classes: Number , String , Collection .
If you pass an object of class Boolean , it returns nothing.
If you pass an Integer , it will return an object corresponding to the Number class.

I tried this:

 private static final Map<Class, Object> cache = new LinkedHashMap<>(); public Object getMapper(Object obj) { for (Iterator<Class> iterator = cache.keySet().iterator(); iterator.hasNext();) { Class key = iterator.next(); if (obj instanceof key) { return cache.get(key); } } return null; } 

But in if he does not see the key and offers to search for Maven. What is the problem?

  • instanceof requires a type name, not a variable of type Class . - VladD
  • @VladD and if there is a class, can I get the type name? - Nikita
  • @Regent I apologize, now I will correct, did not remove the extra pieces - Nikita

1 answer 1

To check whether an object belongs to a class, in this case it is worth using the Class # isInstance method :

 private static final Map<Class, Object> cache = new LinkedHashMap<>(); public Object getMapper(Object obj) { for (Class clazz : cache.keySet()) { if (clazz.isInstance(obj)) { return cache.get(clazz); } } return null; }