Mr. Boy
Mr. Boy

Reputation: 63728

Build a collection of a class' inner classes

In pseudocode I've got:

abstract class Event
{
 ...
 public static class MouseEvent extends Event
 {
  ...
 }
 public static class KeyboardEvent extends Event
 {
  ...
 }
 public static class NetworkEvent extends Event
 {
  ...
 }
}

Is there a neat way to get a collection of the names/details of all the inner-class subclasses? Preferably as a method on the base Event class...

Upvotes: 3

Views: 182

Answers (2)

Ryan Ransford
Ryan Ransford

Reputation: 3222

I believe that you want Event.class.getDeclaredClasses().

import java.util.ArrayList;
import java.util.List;

public class Event {
    public static class MouseEvent extends Event {}
    public static class KeyboardEvent extends Event {}
    public static class NetworkEvent extends Event {}
    public static class NotAnEvent {}

public static List<Class<?>> getDeclaredEvents() {
        final Class<?>[] candidates = Event.class.getDeclaredClasses();
        final List<Class<?>> declaredEvents = new ArrayList<Class<?>>();
        for (final Class<?> candidate : candidates) {
            if (Event.class.isAssignableFrom(candidate)) {
                declaredEvents.add(candidate);
            }
        }
        return declaredEvents;
    }

    public static void main(final String args[]) {
        final List<Class<?>> events = Event.getDeclaredEvents();
        for (final Class<?> event : events) {
            System.out.println("event class name: '" + event.getName() + "'.");
        }
    }
}

Will give you the expected output:

event class name: 'Event$KeyboardEvent'.
event class name: 'Event$MouseEvent'.
event class name: 'Event$NetworkEvent'.

However, I think that you are looking for a more open scanning mechanism which does not limit itself to inner classes. Based on this question, it does not look like there is a straight-forward way to do this.

The Spring framework does something like this with its annotation scanning (see org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider), but their approach is not a straight-forward method call.

Upvotes: 2

dsingleton
dsingleton

Reputation: 1006

    public static void main(String[] args) {
        for (Class c : OuterClass.class.getClasses())
        {
            System.out.println(c.getName());
        }
    }

and then you can have the class of

public class OuterClass {

    public class InnerClass {

    }

    public class InnerClassA {

    }

    public class InnerClassC {

    }
}

The resulting printed statement is

OuterClass$InnerClass
OuterClass$InnerClassA
OuterClass$InnerClassC

Upvotes: 0

Related Questions