Is there a map like data structure that uses Java Class objects as keys but uses fallback to superclasses if no mapping is found? Let me give a short example:
ClassMap<Integer> map = new ClassMap<Integer>();
map.put(Object.class, 1);
map.put(Number.class, 2);
assertEquals(1, map.get(String.class));
assertEquals(2, map.get(Number.class));
assertEquals(2, map.get(Double.class));
I know that I could do the fallback manually, e.g.
WeakHashMap<Class<?>, Integer> map = // snip
Class<?> cls = Double.class;
Integer i;
do {
i = map.get(cls);
cls = cls.getSuperclass();
} while (i == null && cls != null);
Still I’m interested in existing or alternative solutions.
I can’t think of any other data structure that would do a reasonable job. You probably will have to code this yourself. The approach you’ve chosen will perform very well — O(n), where n is the average inheritance depth of the classes you’re going to use as keys. N will be constant (and likely very small) for any reasonable class hierarchy. It’s pretty unlikely that any other data structure will do better, or be any easier to use.
IMO the more interesting question is how to organise the code you’re going to write yourself. One possibility is folding it up as a custom Map implementation:
then it’s at least well contained.