com.softicar.platform.common.core.java.reflection.ClassHierarchyUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of platform-common Show documentation
Show all versions of platform-common Show documentation
The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.
package com.softicar.platform.common.core.java.reflection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
/**
* Utility methods to analyze the hierarchy of a class or interface.
*
* @author Oliver Richers
*/
public class ClassHierarchyUtils {
/**
* Returns all interfaces that the given {@link Class} implements.
*
* @param javaClass
* the class to analyze (never null)
* @return a {@link Set} of all implemented interfaces
*/
public static Set> getAllInterfaces(Class javaClass) {
Objects.requireNonNull(javaClass);
Set> interfaces = new HashSet<>();
forEachClassInHierarchy(javaClass, it -> gatherInterfaces(it, interfaces));
return interfaces;
}
private static void gatherInterfaces(Class theClass, Set> interfaces) {
for (Class theInterface: theClass.getInterfaces()) {
interfaces.add(theInterface);
gatherInterfaces(theInterface, interfaces);
}
}
/**
* Executes the given {@link Consumer} for the given {@link Class} and all
* its super classes.
*
* @param javaClass
* the class (never null)
* @param consumer
* the consumer to execute (never null)
*/
public static void forEachClassInHierarchy(Class javaClass, Consumer> consumer) {
Objects.requireNonNull(javaClass);
Objects.requireNonNull(consumer);
consumer.accept(javaClass);
Optional//
.ofNullable(javaClass.getSuperclass())
.ifPresent(superClass -> forEachClassInHierarchy(superClass, consumer));
}
}