java—如何从泛型类型创建父类的示例,然后使用它调用子类方法?

hfyxw5xn  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(166)

我正在写我的程序,我正试图从一个特定的类运行一个方法,这个方法基于你给程序的字符串。我知道 Class.forName() 但是,我的类不在同一个包中,这会使它变得非常混乱,因为我希望优化我的代码,所以我不希望这样做。相反,我编写了一个定制的类加载器,我可以用它一次加载我想要的所有类。这些类都有一个父类,它有我需要使用的方法,这些类的子类都重写父函数。我希望能够输入子类的名称,然后运行相应的 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
    }
}

不做一个巨大的开关箱塔,这可能吗?谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题