使用 Reflections 动态加载包中的所有 类

Using Reflections to dynamically load all classes in a package

我有一个名为 "func_commands" 的程序包,其中有一堆 类,每个都具有 "cmd" 和 "man" 的功能。我希望能够加载它们而无需特别说明它们的名称,因为我现在正在使用一个界面,并且我希望我的程序是模块化的,以便用户可以添加或删除 类,并且loaded/unloaded 相应地在程序下次重新启动时。

我听说 Reflections 可以做到这一点,但我找不到关于如何做到这一点的工作教程,而且在文档方面我是个白痴。有人知道怎么做吗?

我已经能够使用它来找到扩展我的界面的 类,但我不知道如何加载 类。

    Reflections reflections = new Reflections("func_commands"); //init reflections and point it to the package (I think thats what the string does, I forgot)

    Set<Class<? extends Command>> allClasses = 
            reflections.getSubTypesOf(Command.class); //get the classes from it that extend Commnd

我目前如何加载 类:

for(Command command:CommandArray.commands) {
        command.cmd(e);
        command.man(e);
    };


//meanwhile in CommandArray...
public static Command[] commands = {    
        new ClassA(),
        new ClassB(),
        new ClassC()
};

我希望能够加载它们而无需特别说明它们的名称,因为我现在正在使用一个界面,并且我希望我的程序是模块化的,这样 class es 可以由用户添加或删除,并且 loaded/unloaded 相应地在程序下次重新启动时。

您的意思可能是您希望能够实例化 classes 并且仅通过接口访问它们的 public API。这是非常好的做法。

有多种方法可以实现这一点,您说得对,反射就是其中之一。然而,这是非常昂贵的,它涉及到必须转换实例化的 class。这会从您的程序中删除任何编译时检查。

另一种常见做法是为静态工厂class提供实例化对象的方法。 JDK 就是一个很好的例子。 EnumSet 没有任何构造函数,只有一个静态工厂。在引擎盖下,两个不同的 classes,即 RegularEnumSetJumboEnumSet 是根据底层枚举的大小实例化的。您使用类似的方法在静态工厂中定义 classes 并根据不同的需求交换实现。

有关静态工厂的更多信息,请访问:https://dzone.com/articles/constructors-or-static-factory-methods

已编辑:为反射 class 实例化添加了 link:http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html