Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all inner classes by reflection

Tags:

java

I have the following problem. I have this pretty class and now I want to get all the classes that extend that class (inner classes ) and fill 'classList' with it. ( in an automatic way of course )

public abstract class CompoundReference {

    private static List<Class<? extends CompoundReference>> classList
            = new ArrayList<Class<? extends CompoundReference>>();


    @CompoundKey(gsType = User.class, dbType = UserDetailsMappings.class)
    public static class CUser extends CompoundReference {
    }

    @CompoundKey(gsType = Catalog.class, dbType = CatalogDetailsMappings.class)
    public static class CCatalog extends CompoundReference {
    }

    @CompoundKey(gsType = Product.class, dbType = ProductDetailsMappings.class)
    public static class CProduct extends CompoundReference {
    }

    @CompoundKey(gsType = Category.class)
    public static class CCategory extends CompoundReference {
    }

    @CompoundKey(gsType = Poll.class, dbType = PollDetailsMappings.class)
    public static class CPoll extends CompoundReference {
    }
    // much mroe inner classes

Some manual solution would be just to main such a static block , that is something that I dont want to do.

  static {
        classList.addAll(Arrays.asList(CUser.class, CCatalog.class,
                CProduct.class, CCategory.class,
                CPoll.class, CComment.class, CWebPage.class,
                CReview.class, CPost.class, CMessage.class, CStory.class,CPicture.class));

    }
like image 742
Roman Avatar asked May 24 '10 18:05

Roman


1 Answers

classList.addAll(Arrays.asList(CompoundReference.class.getDeclaredClasses()));

I should note that this isn't safe from a Generics point of view, since the getDeclaredClasses method can return all kinds of classes, not just sublcasses of the enclosing class, it is just an array of Class<?>, so you may need to iterate and confirm/cast as needed for your use case.

like image 158
Yishai Avatar answered Oct 17 '22 18:10

Yishai