-1

So... not entirely sure if this has been answered before, though I suspect it has and I simply didn't understand it with my current knowledge of the language. As such, a tad bit further of an explanation may be nice, the thread I believe that this may be a duplicate of is

Java Pass Method as Parameter

The basic idea of what I would like to do is something like this:

public void doStuff(String parameter, int parameter, Action/Method/Scope/thing action){
    for(parameters){
        action();
    }
}

which would be called like this:

String parameter1;
int parameter2;
doStuff(parameter1, parameter2){
    action
}

this is really generic. Sorry about not having anything specific now. The main thing I'm thinking of is that I've been trying to make an "artillery game" similar to Arcanists (target), or maybe gravitee wars (as a more recent/popular example) the annoying bit is I am frequently working with editing images at a pixel level because the generic bufferedImage/graphic/whatever the normal one & GreenfootImage (greenfoot is the environment I'm using) lack what I want.

really tired right now, please be patient with me. if some of this looks odd of incoherent feel free to ask for clarification, I'm not always the easiest to understand when I'm typing tiredly.

Elijah S
  • 7
  • 6

2 Answers2

1

To "pass a method" in Java 8, you need a matching functional interface, i.e. an interface with only one method, whose parameters and return type matches the method you want to pass.

You can use one of the standard methods in the java.util.function package, or you can write your own. E.g. the standard interfaces has various methods with 0, 1, or 2 parameters.

Since your parameters are different type, you can use BiFunction, or you could create your own like this:

public interface StringIntConsumer {
    void accept(String s, int i);
}

You can now write code to accept such a method:

public void doStuff(String text, int count, StringIntConsumer action) {
    for (int i = 0; i < count; i++) {
        action.accept(text, i);
    }
}

Then call it using a Lambda Expression:

doStuff("Foo", 10, (name, idx) -> {
    // use name and idx here
    // will be called 10 times with idx value 0-9
});

As you can see, the parameter names don't need to match.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

You have described a BiFunction<T, U, R>,

static <T, U, R> R doStuff(T t, U u, BiFunction<T, U, R> func) {
    return func.apply(t, u);
}

And you might call it like

public static void main(String[] args) {
    System.out.println(doStuff("Hello", 1, (x, y) -> x + " " + y));
}

which just prints "Hello 1" - but it wasn't clear what action you wanted to do.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249