【发布时间】:2018-04-05 22:34:17
【问题描述】:
我有一个名为“func_commands”的包,它有一堆类,每个类都有函数“cmd”和“man”。我希望能够在不明确说明它们的名称的情况下加载它们,因为我现在正在使用一个接口,并且我希望我的程序是模块化的,以便用户可以添加或删除类,并相应地加载/卸载在程序下次重新启动时。
我听说 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()
};
【问题讨论】:
-
你的意思是加载类,还是实例化它们?在 Java 中加载类并不是你需要经常做的事情。
-
@SeverityOne 我不确定哪个是哪个,我对 java 比较陌生。我的意思是让他们在某个事件上被召唤。为了清楚起见,我对原始帖子进行了编辑。
标签: java dynamic classloader