如何解决如何从泛型类型创建父类的实例,然后使用它来调用子类方法?
我正在编写程序,并且尝试基于给您程序的String从特定类运行方法。我知道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
}
}
在没有建造大型开关箱塔的情况下有可能吗?谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。