find all classes and interfaces a class extends or implements recursively

后端 未结 8 1218
孤独总比滥情好
孤独总比滥情好 2021-02-12 22:13

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         


        
相关标签:
8条回答
  • 2021-02-12 22:43

    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.

    0 讨论(0)
  • 2021-02-12 22:44

    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
    
    
    0 讨论(0)
提交回复
热议问题