Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way to know the inner classes that a Class has through Reflection in Java?

like image 293
unj2 Avatar asked May 02 '10 02:05

unj2


1 Answers

Yes, 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.

like image 172
BalusC Avatar answered Sep 18 '22 02:09

BalusC