Aragok
Aragok

Reputation: 363

Pass function as parameter to method and return its return Value in Java?

My situation is as follows, I have a bunch of commands e.g.:

someService1.foo()
someService2.bar()

Which are needed to be executed in two different ways, one in a modified security context and some times without modification of the security context. Now my plan was to write a Executor which should have structure like this:

public Object runCommand(Runnable command){
  if(someCondition){
    //run command in modified context
  } else {
    //just run the command
  }
}

My major Problem is how to get the return value of the command back to the calling method. Because the run() of Runnable has a return type of void. So i thought about using Callable to achieve this. But is there clean generic approach for this problem?

Upvotes: 0

Views: 1474

Answers (1)

Veselin Davidov
Veselin Davidov

Reputation: 7081

Well instead of using Runnable you can create your own interface (Runnable is also interface). If you want the return type to be generic you can create something like:

@FunctionalInterface
interface MyCommand<T> {
    public T execute();
}

Then your code will become:

public <T> T runCommand(MyCommand<T> command){
  if(someCondition){
    //Run it in context or whatever 
    return command.execute();
  } else {
    return command.execute();
  }
}

And you can use it like (full code here):

public class Test{

 public static void main(String[] args) {
    Test test=new Test();
    String result1=test.runCommand(test::stringCommand);
    Integer result2=test.runCommand(test::integerCommand);
    Boolean result3 = inter.runCommand(new MyCommand<Boolean>() {
        @Override
        public Boolean execute() {
            return true;
        }
    });
 }

 public String stringCommand() {
    return "A string command";
 }

 public Integer integerCommand() {
    return new Integer(5);
 }

 public <T>T runCommand(MyCommand<T> command){
    return command.execute();
 }
}

Upvotes: 1

Related Questions