org.bson.util.ClassAncestry Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sequoiadb-driver Show documentation
Show all versions of sequoiadb-driver Show documentation
Java client driver for SequoiaDB
package org.bson.util;
import static java.util.Collections.unmodifiableList;
import static org.bson.util.CopyOnWriteMap.newHashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
class ClassAncestry {
private static final ConcurrentMap, List>> _ancestryCache = newHashMap();
/**
* getAncestry
*
* Walks superclass and interface graph, superclasses first, then
* interfaces, to compute an ancestry list. Supertypes are visited left to
* right. Duplicates are removed such that no Class will appear in the list
* before one of its subtypes.
*
* Does not need to be synchronized, races are harmless as the Class graph
* does not change at runtime.
*/
public static List> getAncestry(Class c) {
final ConcurrentMap, List>> cache = getClassAncestryCache();
while (true) {
List> cachedResult = cache.get(c);
if (cachedResult != null) { return cachedResult; }
cache.putIfAbsent(c, computeAncestry(c));
}
}
/**
* computeAncestry, starting with children and going back to parents
*/
private static List> computeAncestry(Class> c) {
final List> result = new ArrayList>();
result.add(Object.class);
computeAncestry(c, result);
Collections.reverse(result);
return unmodifiableList(new ArrayList>(result));
}
private static void computeAncestry(Class c, List> result) {
if ((c == null) || (c == Object.class)) { return; }
// first interfaces (looks backwards but is not)
Class>[] interfaces = c.getInterfaces();
for (int i = interfaces.length - 1; i >= 0; i--) {
computeAncestry(interfaces[i], result);
}
// next superclass
computeAncestry(c.getSuperclass(), result);
if (!result.contains(c)) result.add(c);
}
/**
* classAncestryCache
*/
private static ConcurrentMap, List>> getClassAncestryCache() {
return (_ancestryCache);
}
}