测试BiConsumer时出现编译错误

时间:2017-01-05 15:19:35

标签: java lambda java-8

我在下面写了接受BiConsumer<Object, Object>的方法,当我传递方法testBiConsumer(String a, String b)的方法引用时,我收到一个编译错误说明:

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

如果我将BiConsumer从BiConsumer<Object, Object>更改为BiConsumer<String , String >,它就可以了。

如何使下面的代码工作?我希望public static void biConsumerTest(String a, String b, BiConsumer<String, String> biConsumer)是通用的。

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);
        }
    }

1 个答案:

答案 0 :(得分:3)

代码看起来有点滑稽,并且不清楚你实际上要实现什么,但要使其成为通用的:

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);
    }
}