构建类的内部类的集合

时间:2012-02-22 14:50:17

标签: java

在伪代码中我得到了:

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

是否有一种简洁的方法来获取所有内部类子类的名称/详细信息的集合?最好作为基础Event类的方法......

2 个答案:

答案 0 :(得分:2)

我相信你想要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() + "'.");
        }
    }
}

会给你预期的输出:

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

但是,我认为您正在寻找一种更开放的扫描机制,它不局限于内部类。基于this问题,看起来没有直接的方法来做到这一点。

Spring框架通过其注释扫描执行类似的操作(请参阅org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider),但他们的方法不是直接的方法调用。

答案 1 :(得分:0)

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

然后你可以拥有

public class OuterClass {

    public class InnerClass {

    }

    public class InnerClassA {

    }

    public class InnerClassC {

    }
}

结果打印的声明是

OuterClass$InnerClass
OuterClass$InnerClassA
OuterClass$InnerClassC