All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.softicar.platform.common.core.java.reflection.ClassHierarchyUtils Maven / Gradle / Ivy

Go to download

The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.

There is a newer version: 50.0.0
Show newest version
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));
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy