I need a way to write a command call that will be executed in compiled code. However, the command will be store in a database as a String because it’s configurable by the user. Each command would match a class but there could be multiple commands that need to be executed with input parameters.
How is the best way of handling this?
Example Class that would be called:
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();
}
}
Example Method that would call the command:
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)'
}
}
The call to ‘org.example.CreateUser.create(user)’ will be stored in a database and I need to be able to run it from a function that will get it out of the database and call it adding the parameter User.
Have you considered using the Command Pattern?
Basically, you create an interface like
Then, for every method that the user could call, you create class that implements that interface. Each implementation^ calls their associate method in the body of their
doIt()method. Then, you store each user’s chosen implementation class’s cannononical name as a string field in the database. When the user logins you fetch than field, instantiate the instance using Class.forName(String), and cast the return toDoStuff. Then, whenever the user’s chose method would be called calluserStuffDoer.doIt()and their chosen method will be called.If there is a near infinite number of methods a user could call you will have to use reflection and store class and method names and how to get the method data etc.
^ The implementation classes will need to have empty constructors.