Java Pass Method as Parameter

后端 未结 16 1033
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  無奈伤痛
    2020-11-22 02:52

    Here is a basic example:

    public class TestMethodPassing
    {
        private static void println()
        {
            System.out.println("Do println");
        }
    
        private static void print()
        {
            System.out.print("Do print");
        }
    
        private static void performTask(BasicFunctionalInterface functionalInterface)
        {
            functionalInterface.performTask();
        }
    
        @FunctionalInterface
        interface BasicFunctionalInterface
        {
            void performTask();
        }
    
        public static void main(String[] arguments)
        {
            performTask(TestMethodPassing::println);
            performTask(TestMethodPassing::print);
        }
    }
    

    Output:

    Do println
    Do print
    

提交回复
热议问题