I use a heterogeneous container like this one . I can easily add and remove objects from the container:
Favorites f = new Favorites(); f.putFavorite(String.class, "Java"); String someString = f.getFavorite(String.class);
But there seems to be no easy way to iterate over such a container. I can add the keySet() method to the Favorites class and simply return the key set of the internal Map object:
public Set<Class<?>> keySet() { return favorites.keySet(); }
Now I would like to iterate over the keys, use the keys to get the associated values, and call some methods on the received objects:
for (Class<?> klass : f.keySet()) {
I thought I could access the methods of the objects stored in my container by calling klass.cast(f.getFavorite(klass)).SOME_METHOD() , but it doesnβt work either (which means I cannot access which any methods other than Object methods).
Let's say that in my use case, I would like to check the interfaces of all these objects, which I iterate over and act according to the detected interface. Suppose also that I can have dozens of objects of different classes, and they all implement one of three interfaces.
The only solution I can think of is to isinstance my code with dozens of isinstance checks, but I would prefer a less cumbersome approach (for example, checking if a given object implements one of the three interfaces).
source share