Is there a way to know the inner classes that a Class has through Reflection in Java?
views:
63answers:
3Yes, use Class#getDeclaredClasses()
for this. You only need to determine if it's an inner class or a nested (static) class by checking its modifiers. Assuming that Parent
is the parent class, here's a kickoff example:
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 only doesn't cover anonymous classes, but seeing your previous question on the subject, I don't think you're explicitly asking for them.
No, unfortunately, for the same reason why you cannot enumerate regular classes in a package.
Inner classes are really just ordinary classes at runtime. The compiler does some tweaking to get around the usual access rules, For example, the inner class appears to be able to access private fields and methods of the enclosing class - it can do this because the compiler creates a non-private accessor 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 these can't be reliably enumerated, so the general answer is no, not possible.
However, it can be solved in specific cases. If you know the JARs you are using, then you can iterate across all files in the JAR, looking for files of the pattern yourpakage.YourClass$<something>.class
where <something>
is one or more characters.
EDIT: There are various types of inner class:
- declared members, 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 the correct one. If you want all inner classes, then getDeclaredClasses
unfortunately won't work. See SDN Bug 4191731. In that case, you might try one of the class enumeation methods proposed in the link (such as scanning the JAR file.)
Yes, there is a trick to do that. See an old post about locating resources. Knowing your class(let's say com.domain.api.ClassA), extract the package name, convert the package to a path(replace '.' with '/' and you get com/domain/api) scan for all the files with extension .class in that folder and retain only those files which starts with your class name(ClassA$xxxxx), those are the inner classes for class ClassA