lqdev
lqdev

Reputation: 403

Pass function to a method and then use that function in another method

The title might confuse you, but here's what I am asking for.

I have 2 classes: Parser and CommandArray.

In the CommandArray I want to have a function that will add a command to my array, and look a little bit like this: addCommand(String name, [Type] callback). Then in the Parser I want to have that CommandArray, so the Parser can loop through an array of strings, find the name, parse that line, then if everything is correct, run callback and pass the line to it.

Here's some pseudocode to illustrate what I'm trying to do a little better:

myCallback = function(line)
  print(line)
end

function parseLine(command, callback) -- command is the line
  -- do the parsing
  callback(command)
end

parseLine("Rectangle 32, 32, 64, 64", myCallback)

Disclaimer: This code wasn't tested

Is there any easy way to do it in Java?

Upvotes: 2

Views: 46

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

I am not 100% sure what your end result is but you can accomplish this with the use of functional interfaces.

A quick example:

The code below would be the equivalent of your pseudocode:

Consumer<String> myCallback = System.out::println;

then the parseLine function will become:

public void parseLine(String command, Consumer<String> callback){
       callback.accept(command);
}

then this line:

parseLine("Rectangle 32, 32, 64, 64", myCallback)

will become:

parseLine("Rectangle 32, 32, 64, 64", myCallback);

for more information about all the available functional interfaces and what you can do with them check out the java.util.function package.

Upvotes: 2

Related Questions