I was wondering if there was an easy way of determining the complete list of Types that a Java class extends or implements recursively?
for instance:
cla
From the question How do you find all subclasses of a given class in Java?, this answer might be helpful:
Using the class PojoClassImpl.java you can get the super class by calling method getSuperClass()
. I think that is sufficient for you to write a recursive method.
In Java8
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ClassUtil {
public static Set<Class<?>> getAllExtendedOrImplementedTypesRecursively(final Class<?> clazz) {
return walk(clazz)
.filter(Predicate.isEqual(java.lang.Object.class).negate())
.collect(Collectors.toSet());
}
public static Stream<Class<?>> walk(final Class<?> c) {
return Stream.concat(Stream.of(c),
Stream.concat(
Optional.ofNullable(c.getSuperclass()).map(Stream::of).orElseGet(Stream::empty),
Arrays.stream(c.getInterfaces())
).flatMap(ClassUtil::walk));
}
}
Test Code:
import java.util.Set;
class Test {
public static void main(String[] args) {
final Set<Class<?>> set = ClassUtil.getAllExtendedOrImplementedTypesRecursively(Foo.class);
set.stream().map(Class::getName).forEach(System.out::println);
}
class Foo extends Bar implements I1, I2 {}
class Bar implements I3 {}
interface I1 extends I4, I5 {}
interface I2 {}
interface I3 {}
interface I4 {}
interface I5 {}
}
Output:
Test$Foo Test$Bar Test$I2 Test$I5 Test$I1 Test$I3 Test$I4