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

前端 未结 4 1685
我寻月下人不归
我寻月下人不归 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:10

    You can use Java 8 method references. You can use the :: 'operator' to grab a method reference from an object.

    import java.util.function.IntConsumer;
    
    class Test {
        private int i;
        public Test() { this.i = 0; }
        public void inc(int x) { this.i += x; }
        public int get() { return this.i; }
    
        public static void main(String[] args) {
            Test t = new Test();
            IntConsumer c = t::inc;
            c.accept(3);
            System.out.println(t.get());
            // prints 3
        }
    }
    

    You just need a @FunctionalInterface that matches the signature of the method you want to store. java.util.function contains a selection of the most commonly used ones.

提交回复
热议问题