我需要一种方法来编写将在编译代码中执行的命令调用。但是,该命令将作为字符串存储在数据库中,因为它可由用户配置。每个命令都匹配一个类,但可能有多个命令需要使用输入参数执行。
如何处理这个问题最好?
将调用的示例类:
public class CreateUser {
protected User user;
public static void create(User user){
CreateUser cu = new CreateUser(user);
cu.newUserFunction();
}
public CreateUser(User user){
this.user = user;
}
public void newUserFunction(){
doSomething();
}
}
调用命令的示例方法:
public void createUser(User user){
dclCommand.createUser(user.getUsername(), user.getPassword());
// Get special commands to run after user is created
List<Command> cmds = this.dbRepository.findCommand(database, Method.CREATE_USER);
for(Command cmd : cmds){
// Here is where the cmd will be executed with input parameters
// In example the command executed would be 'org.example.CreateUser.create(user)'
}
}
对“org.example.CreateUser.create(user)”的调用将存储在数据库中,我需要能够从一个函数中运行它,该函数会将它从数据库中取出并调用它添加参数用户。
最佳答案
您是否考虑过使用 Command Pattern ?
基本上,您创建一个类似
的界面interface DoStuff{
void doIt();
}
然后,对于用户可以调用的每个方法,您创建实现该接口(interface)的类。每个实现^ 在它们的 doIt()
方法的主体中调用它们的关联方法。然后,您存储每个用户选择的实现类的 cannononical name作为数据库中的字符串字段。当用户登录时获取比字段,使用 Class.forName(String) 实例化实例,并将返回值转换为 DoStuff
。然后,每当调用用户选择的方法时,调用 userStuffDoer.doIt()
并调用他们选择的方法。
如果用户可以调用的方法数量几乎是无限的,您将不得不使用 reflection并存储类和方法名称以及如何获取方法数据等。
^ 实现类需要有空的构造函数。
关于java - 在java中创建动态函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9608408/