Getting all inner classes by reflection

I have the following problem. I have this cool class, and now I want to get all the classes that extend this class (inner classes) and populate it with "classList". (in automatic mode, 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 the main such static block that I would not 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)); } 
+6
java
source share
2 answers
 classList.addAll(Arrays.asList(CompoundReference.class.getDeclaredClasses())); 

I should note that this is unsafe from the point of view of Generics, since the getDeclaredClasses method can return all types of classes, not just subclasses of the surrounding class, it is just an array from Class<?> , So you may need to iterate and confirm / cast in case necessary for your use case.

+8
source share

Class.getDeclaredClasses

Returns an array of class objects reflecting all classes and interfaces declared by members of the class represented by this class object. This includes public, secure, standard (batch) access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces.

I'm not sure that the last exception applies to inner classes, which are also a subclass ... Check it out.

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

0
source share

All Articles