jpganz18
jpganz18

Reputation: 5878

how to have a generic as parameter to receive a function that applies later a specific method?

I am trying to do this

First I have an interface like this:

public void doSomething (String input, MyClass myMethod);

and at the implementation I had

public void doSomething (String input, MyClass myMethod){
    myMethod.mySpecificMethod(input2);
}

So now I was checking the java.util.function class and I found out that there is a FunctionalInterface Function.

So far I just try to replace MyClass myMethod with this Function but Im sure there are better ways (also this doesnt work).

Any idea how to? When using generics later I cannot invoke my method, should I just cast the generic to the desired class?

Upvotes: 2

Views: 117

Answers (1)

Eran
Eran

Reputation: 393956

Based on your example, it looks like doSomething requires a method that accepts a String and returns nothing. This fits the Consumer<String> interface:

public void doSomething (String input, Consumer<String> consumer){
    consumer.accept(input);
}

And you call it with:

doSomething ("some string", myMethod::mySpecificMethod);

where myMethod is an instance of MyClass.

Upvotes: 3

Related Questions