Reputation: 3466
I have written below method which accept BiConsumer<Object, Object>
, when I pass the method reference of method testBiConsumer(String a, String b)
I am getting a compilation error stating:
Multiple markers at this line
- The method biConsumerTest(String, String, BiConsumer<Object,Object>) in the type Test is not applicable for the arguments (String, String,
Test::testBiConsumer)
- The type Test does not define testBiConsumer(Object, Object) that is applicable here
If I change BiConsumer from BiConsumer<Object, Object>
to BiConsumer<String , String >
it works just fine.
How do I make below code work? I want public static void biConsumerTest(String a, String b, BiConsumer<String, String> biConsumer)
to be generic.
public class Test {
public static void main(String[] args){
Test.biConsumerTest("A", "B", Test::testBiConsumer);
}
public static void biConsumerTest(String a, String b, BiConsumer<Object, Object> biConsumer){
biConsumer.accept(a, b);
}
public static void testBiConsumer(String a, String b) {
System.out.println(a);
System.out.println(b);
}
}
Upvotes: 2
Views: 227
Reputation: 120858
The code looks a bit funny and unclear what you actually what to achieve, but to make it generic:
public class Test {
public static void main(String[] args) {
Test.biConsumerTest("A", "B", Test::testBiConsumer);
}
public static <T> void biConsumerTest(T a, T b, BiConsumer<T, T> biConsumer) {
biConsumer.accept(a, b);
}
public static <S> void testBiConsumer(S a, S b) {
System.out.println(a);
System.out.println(b);
}
}
Upvotes: 3