java - 如何从 Generic 类型创建父类的实例,然后使用它来调用子类方法?
问题描述
我正在编写我的程序,并且我正在尝试根据您提供给程序的字符串从特定类中运行一个方法。我知道Class.forName()
,但是我的类不在同一个包中,而且处理起来非常混乱,因为我希望优化我的代码,我宁愿不这样做。相反,我编写了一个自定义的 ClassLoader,我可以用它来一次加载我想要的所有类。这些类都有一个父类,它具有我需要使用的方法,并且这些类的子类都覆盖了父函数。如果可能的话,我将能够输入子类的名称,然后运行其相应的run()
方法,而无需进行大量类型检查(我有大约 20 个不同的子类)。到目前为止,这是我的代码:
content = content.substring(prefix.length());
OweoClassLoader ocl = new OweoClassLoader();
String[] blacklist = {"Command", "ToggleableCommand", "NonToggleableCommand"};
//The array of child classes I want to use
ArrayList<Class<?>> commandClasses = ocl.getClasses(System.getProperty("user.dir") + "/bin/io/github/epicoweo/commands", blacklist);
//Just capitalizing the first letter of the input string
char[] command = content.split("\\s+")[0].toCharArray();
String str = "";
str += Character.toString(command[0]).toUpperCase();
if(command.length > 1) {
for(int i = 1; i < command.length; i++) {
str += command[i];
}
}
for(Class<?> c : commandClasses) {
if(Command.class.isAssignableFrom(c)) { //Command is the parent class, which also has a run method
//right here I want to be able to call
c.getDeclaredConstructor().newInstance().run(); //the child class's run method, not the parent's
}
}
如果不制造一个巨大的开关盒塔,这可能吗?谢谢!
解决方案
推荐阅读
- xml - IBM WebSphere Liberty Datasource 能否从 server.xml 拆分为包含文件?
- ios - iOS Firebase 动态链接不适用于百分比编码的 URL
- java - 如何使用 MockMvc 测试 REST 控制器
- c# - nullcheck 的返回语句返回 NullReferenceException
- c# - C# 连接到 SQL Server 时处理 TCP 超时
- javascript - 如果值存在于工作表 1 和工作表 2 中,则复制行并将其粘贴到工作表 3。谷歌表格。Google Apps 脚本
- python - 如何将可选参数从一个函数传递给另一个函数,这也是第一个函数的参数?
- jenkins - Jenkins 共享管道库 - 获取构建状态
- exception - 在 E21 RISCV 处理器中由 mret 从 ISR 返回后获取异常(存储错误访问)
- pentaho - 从 Kettle PDI 连接到 MSSQL