首页 > 解决方案 > 如何从 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
    }
}

如果不制造一个巨大的开关盒塔,这可能吗?谢谢!

标签: javaclassgenerics

解决方案


推荐阅读