Java8 Method Reference

Source: Internet
Author: User

Content Introduction:
Method Reference Demo Detailed
Reference by using 5 syntax methods
Method Reference Usage Summary

    1. Method reference Demo in Java8
      1.1 Method references the background that appears
      When we use lambda expressions, the code we actually pass in is a solution: what parameters to do what.
      So consider a situation where, if we have the same scheme in place for the operation specified in lambda, is it necessary to write repetitive logic?
      1.2 The problem leads?
   //函数式接口,用于打印字符串.    @FunctionalInterface    interface Print{        public void print(String s);    }    //使用lambda表达式完成案例测试.    public class PrintDemo {        public static void main(String[] args) {            //Lambda方式解决            print(s -> {System.out.println(s);}, "hello");        }        public static void print(Print p,String s){            p.print(s);        }    }??    输出结果:            hello

1.3 Problem finding and solving
The problem with this code is that there is already a ready-made implementation of the string for the console printout, which is the println (String) method in the System.out object. Since what Lambda wants to do is to invoke the println (String) method, why do you call it manually?
Can you omit the syntax format of lambda (although it is already fairly concise)? As long as "routing" was over:

//函数式接口,用于打印字符串.    @FunctionalInterface    interface Print{        public void print(String s);    }    //使用lambda表达式完成案例测试.    public class PrintDemo {        public static void main(String[] args) {            //方法引用解决方式            //请注意其中的双冒号“::”写法,这被称为“方法引用”,而双冒号是一种“引用运算符”。            print(System.out :: print,"world");        }        public static void print(Print p,String s){            p.print(s);        }    }??    输出结果:            world

1.4 Summary of method reference cases
In the example above, there is an overloaded println (String) method in the System.out object that is exactly what we need. So for the function interface parameters of the Printstring method, compare the following two kinds of notation:
Lambda expression: S--System.out.println (s);
Method reference: System.out::p rintln
The first semantic means: After getting the parameters, the lambda hand is passed to the System.out.println method to deal with it. The second equivalent of the semantics of the method refers to: direct System.out in the println methods to replace the lambda. The execution of the two methods is exactly the same, and the second method refers to the wording of the reuse of the existing scheme, more concise. 1.5 Reference operators
The double colon "::" is a reference operator, and the expression it is in is referred to as a method reference. If the function scheme that the lambda is expressing already exists in the implementation of a method, then you can refer to the method as a substitute for the lambda by a double colon.
2. Reference by 5 syntax usage methods
2.1 Referencing member methods by object name
?

  //函数式接口    @FunctionalInterface    interface Printable{        public void print(String s);    }?    //已存在的类,类中有打印字符串的方法.    class AlreadyExistPrint{        public void PrintString(String s){        System.out.println(s);    }??    //测试通过对象名进行方法引用.    public class ObjectMethodReference {        public static void main(String[] args) {            //通过对象名引用方法            AlreadyExistPrint ap = new AlreadyExistPrint();            print(ap :: PrintString,"java");        }        public static void print(Printable p,String s){            p.print(s);        }?    }?    输出结果:            java

2.2 Referencing static methods by class name

  //函数式接口    @FunctionalInterface    interface MyMath{        int max(int a, int b);    }?    //已存在的类    这里使用JDK提供的Math类中的静态方法max(int a,int b);??    //测试通过类名引用静态方法.    public class ClassStaticMethod {        public static void main(String[] args) {            //通过Math类的类名引用静态方法max();            int max = getMax(Math :: max, 10, 20);            System.out.println(max);        }        public static int getMax(MyMath lambda ,int a,int b){            return lambda.max(a, b);        }?    }?    输出结果:            20

2.3 Referencing member methods by class name

The 
 /* Member method needs to rely on an object to execute, so the member method cannot execute when the object does not exist.    If you want a reference to a member method to have only the class name and not the object name, it is a bit more complicated: You must specify an object instance for which to execute the member method.    */? Adding an object instance to a parameter in a function interface: @FunctionalInterface interface printable{public void print (Alreadyexistprint A, String    s);    }?        already exists class alreadyexistprint{public void Printstring (String s) {System.out.println (s);    }?    }?    The test refers to a member method by its class name.            public class Classmethod {public static void main (string[] args) {//The member method is referenced by the class name; Lambda mode implementation://Semantic parsing: Take object A to call A's Print method printing s print ((a,s), {a.printstring (s);},new ALREADYEXISTPR            Int (), "Hello");        Simplified notation: Method references (referencing member methods by class name) print (alreadyexistprint:: Printstring,new alreadyexistprint (), "Hello");        } public static void print (Printable p, alreadyexistprint a,string s) {p.print (a,s);    }?    }? Output result: Hello Hello  

2.4 Referencing member methods with super

    //函数式接口    @FunctionalInterface    interface Eat{        void eat(String food);    }?    //已存在的类    class Animal{        public void eat(String food){            System.out.println("吃:"+food);        }    }?    //Animal的子类    class Cat extends Animal{        @Override        public void eat(String food) {            //通过super引用父类的方法.            method(super :: eat,food);        }        public void method(Eat e, String s){            e.eat(s);        }    }??    //测试通过类名引用成员方法.    public class SuperMethod {        public static void main(String[] args) {            Cat c = new Cat();            c.eat("鱼");        }?    }?    输出结果:            吃鱼

2.5 Referencing member methods by this

    //函数式接口    interface shopping {        void buy(int money);    }?    //已存在的类    class Man {        //男人将来都要买个属于自己的房子.        public void buyHouse(int money) {            System.out.println("买套房子消费:"+money);        }        //结婚就得购物,买买买啊.        public void marry(shopping lambda,int money) {            lambda.buy(money);        }        //开心方法.男人要想开心.就得结婚        public void beHappy() {            //通过this引用成员方法.            marry(this::buyHouse,1000000);        }    }??    //测试通过类名引用成员方法.    public class ThisMethod {?        public static void main(String[] args) {            Man man = new Man();            man.beHappy();        }    }??    输出结果:            买套房子消费:1000000

3. Summary of method Reference usage
? (1) lambda expression: S--System.out.println (s); (2) method reference: System.out::p rintln

The first semantic means: After getting the parameters, the lambda hand is passed to the System.out.println method to deal with it.
?
The second equivalent of the semantics of the method refers to: direct System.out in the println methods to replace the lambda.
The execution of the two methods is exactly the same, and the second method refers to the wording of the reuse of the existing scheme, more concise.
?
The functional interface is the basis of lambda, and the method reference is the twin of lambda.

Java8 Method Reference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.