find all classes and interfaces a class extends or implements recursively

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

    The following implementation of the method does what the OP requires, it traverses the inheritance hierarchy for every class and interface:

    public static Set> getAllExtendedOrImplementedTypesRecursively(Class clazz) {
        List> res = new ArrayList<>();
    
        do {
            res.add(clazz);
    
            // First, add all the interfaces implemented by this class
            Class[] interfaces = clazz.getInterfaces();
            if (interfaces.length > 0) {
                res.addAll(Arrays.asList(interfaces));
    
                for (Class interfaze : interfaces) {
                    res.addAll(getAllExtendedOrImplementedTypesRecursively(interfaze));
                }
            }
    
            // Add the super class
            Class superClass = clazz.getSuperclass();
    
            // Interfaces does not have java,lang.Object as superclass, they have null, so break the cycle and return
            if (superClass == null) {
                break;
            }
    
            // Now inspect the superclass 
            clazz = superClass;
        } while (!"java.lang.Object".equals(clazz.getCanonicalName()));
    
        return new HashSet>(res);
    }    
    

    I tested with JFrame.class and I got the following:

    Set> classes = getAllExtendedOrImplementedTypesRecursively(JFrame.class);
    for (Class clazz : classes) {
        System.out.println(clazz.getName());
    }
    

    Output:

    java.awt.Container
    java.awt.Frame
    javax.swing.JFrame
    javax.swing.TransferHandler$HasGetTransferHandler
    java.awt.Window
    javax.accessibility.Accessible
    javax.swing.RootPaneContainer
    java.awt.Component
    javax.swing.WindowConstants
    java.io.Serializable
    java.awt.MenuContainer
    java.awt.image.ImageObserver
    

    UPDATE: For the OP's test case it prints:

    test.I5
    test.Bar
    test.I2
    test.I1
    test.Foo
    test.I3
    test.I4
    

提交回复
热议问题