Java 8:如何将静态方法用作另一种方法的参数?

时间:2022-06-05 02:34:25

My situation:

class Test {
    private static void xxx(String s) throws SQLException {
        System.out.println(s);
    }
    private static void yyy(Consumer<String> f) {
        try {
            f.apply('hello');
        } catch (SQLException e) {
            System.out.println("error");
        }
    }
    public static void main(String args[])() {
        yyy(xxx);  // <-- not working!!
    }
}

What I'm trying to do is to pass a static method as a parameter for another static method. I think that the correct way to declare the signature of the method yyy is with Consumer, but I'm not really sure about the other part, passing xxx as the parameter.

我要做的是将静态方法作为另一个静态方法的参数传递。我认为声明yyy方法签名的正确方法是使用Consumer,但我不确定另一部分,将xxx作为参数传递。

A possible solution I've found is to write

我发现一个可能的解决方案是写

yyyy(s -> xxx(s));

But it looks ugly and it doesn't really work if xxx throws exceptions.

但它看起来很难看,如果xxx抛出异常,它就无法正常工作。

By using

yyy(Test::xxx);

I got this error

我收到了这个错误

error: incompatible thrown types SQLException in method reference

2 个解决方案

#1


2  

You can use a method reference:

您可以使用方法参考:

class Test {
    private static void xxx(String s) {
        //do something with string
    }
    private static void yyy(Consumer<String> c) {
        c.accept("hello");
    }
    public static void zzz() {
        yyy(Test::xxx);
    }
}

#2


1  

You can try below code

你可以尝试下面的代码

class Test {
    private static Consumer<String>  xxx(String s) {
        //do something with string
        return null;// return Consumer for now passing null
    }

    private static void yyy(Consumer<String> f) {
        //do something with Consumer
    }

    public static void zzz(){
        yyy(xxx("hello")); 
    }
}

#1


2  

You can use a method reference:

您可以使用方法参考:

class Test {
    private static void xxx(String s) {
        //do something with string
    }
    private static void yyy(Consumer<String> c) {
        c.accept("hello");
    }
    public static void zzz() {
        yyy(Test::xxx);
    }
}

#2


1  

You can try below code

你可以尝试下面的代码

class Test {
    private static Consumer<String>  xxx(String s) {
        //do something with string
        return null;// return Consumer for now passing null
    }

    private static void yyy(Consumer<String> f) {
        //do something with Consumer
    }

    public static void zzz(){
        yyy(xxx("hello")); 
    }
}