How can I store a method in a variable in Java 8?

前端 未结 4 1683
我寻月下人不归
我寻月下人不归 2020-12-03 06:28

Is it possible to store a method into a variable? Something like

 public void store() {
     SomeClass foo = ;
     //...
     String          


        
4条回答
  •  抹茶落季
    2020-12-03 07:19

    Yes, you can have a variable reference to any method. For simple methods it's usually enough to use java.util.function.* classes. Here's a working example:

    import java.util.function.Consumer;
    
    public class Main {
    
        public static void main(String[] args) {
            final Consumer simpleReference = Main::someMethod;
            simpleReference.accept(1);
    
            final Consumer another = i -> System.out.println(i);
            another.accept(2);
        }
    
        private static void someMethod(int value) {
            System.out.println(value);
        }
    }
    

    If your method does not match any of those interfaces, you can define your own. The only requirement is that is must have a single abstract method.

    public class Main {
    
        public static void main(String[] args) {
        
            final MyInterface foo = Main::test;
            final String result = foo.someMethod(1, 2, 3);
            System.out.println(result);
        }
    
        private static String test(int foo, int bar, int baz) {
            return "hello";
        }
    
        @FunctionalInterface // Not required, but expresses intent that this is designed 
                             // as a lambda target
        public interface MyInterface {
            String someMethod(int foo, int bar, int baz);
        }
    }
    

提交回复
热议问题