开发者

Getting all inner classes by reflection

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,C开发者_运维问答Picture.class));

    }


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.


Class.getDeclaredClasses

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. This includes public, protected, default (package) access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces.

I'm not sure if the last exclusion applies to inner classes that also are subclasess... Check it.

Your question, BTW, sort of mixes those concepts (inner classes and subclasses), I hope you understand that those are orthogonal concepts: I assume you are actually interested in listing all the inner classes (that, in your case, happen to be also subclasses).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜