find all classes and interfaces a class extends or implements recursively

后端 未结 8 1209
孤独总比滥情好
孤独总比滥情好 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:36

    The key you want is in the Class#getSuperclass() method:

    public static Set> stuff(Class target) {
        Set> classesInterfaces = new HashSet<>();
        classesInterfaces.add(target);
        classesInterfaces.addAll(Arrays.asList(target.getInterfaces());
    
        Class superClass = target.getSuperclass();
        if(superClass != null)
            classesInterfaces.addAll(stuff(superClass));
    }
    

提交回复
热议问题