Is there a way to get the InnerClasses list through Reflection in Java?

Is there a way to find out the inner classes that a class has through Reflection in Java?

+4
source share
3 answers

Yes, use Class#getDeclaredClasses() for this. You only need to determine if it is an inner class or a nested (static) class by checking its modifiers. Assuming Parent is a parent class, here is an example run:

 for (Class<?> cls : Parent.class.getDeclaredClasses()) { if (!Modifier.isStatic(cls.getModifiers())) { // This is an inner class. Do your thing here. } else { // This is a nested class. Not sure if you're interested in this. } } 

Note: this does not apply to anonymous classes, but when I see your previous question on this, I don’t think you are explicitly asking for them.

+6
source

No, unfortunately, for the same reason why you cannot list ordinary classes in a package.

Inner classes are really ordinary classes at runtime. The compiler does some tweaking to get around normal access rules. For example, an inner class appears to be able to access the private fields and methods of the enclosing class β€” it can do this because the compiler creates a non-unit access function that is used by the inner class. See Java in a nutshell - how inner classes work for details.

Inner classes are regular classes, and they cannot be reliably listed, so a general answer is not possible.

However, it can be resolved in specific cases. If you know the JAR files that you use, you can yourpakage.YourClass$<something>.class over all the files in the JAR by looking for yourpakage.YourClass$<something>.class template files, where <something> is one or more characters.

EDIT: There are various types of inner class:

  • declared elements such as interfaces and classes
  • Anonymous classes and local classes

If you only care about the first case, then BalusC's answer using getDeclaredClasses is correct. If you want all the inner classes, then getDeclaredClasses , unfortunately, will not work. See Error SDN 4191731 . In this case, you can try one of the enumation methods of the class suggested in the link (for example, scanning a JAR file.)

0
source

Yes, there is a trick. See Old Resource Search Post. Knowing your class (say com.domain.api.ClassA), extract the package name, convert the package to a path (replace "." With "/" and you will get the com / domain / api command) for all files with the .class extension in to this folder and save only those files that begin with your class name (ClassA $ xxxxx), these are internal classes of the ClassA class

0
source

Source: https://habr.com/ru/post/1308574/


All Articles