This is the 9th day of my participation in Gwen Challenge

Method references and constructor references

A method reference is a quick way to point the implementation of a Lambda expression to an already implemented method. Class name :: Class methods correspond to Lambda expressions (a,b...). -> Class name. Class methods (a,b... The instance method corresponds to Lambda expressions (a,b...). Instance methods (a,b...) Class name :: Instance methods correspond to Lambda expressions (a,b...). ->a. Instance method (b...) Class name ::new corresponds to Lambda expressions (a,b...) - > new class name (a, b,...).Copy the code

1. Class methods

Let's start with the first method reference: class method reference. Public class Test {public static void main(String[] args) {public static void main(String[] args) {Change Change = s -> integer.valueof (s); // Call the change() method to convert Integer val1= change.change("1012"); System.out.println(val1); // use a reference method instead of a Lambda expression Change c = Integer::valueOf; }} interface Change{/** * @param s String * @return Change a String to a number */ Integer Change (String s); }Copy the code

2. Reference instance methods of specific objects

Change c2 = s -> "change1".indexof (s); // Call the change() method on the c2 object Integer val3 = c2.change("100"); System.out.println(val3); // Replace the Lambda expression with method reference Change c3 = "change1"::indexOf;Copy the code

3. Reference instance methods of certain objects

Public class Test {public static void main(String[] args) {MyTest mt = (a,b,c) -> a.substring(b,c); String STR = mt.test("I Love Java",2,6); System.out.println(str); MyTest mt1 = String::substring; MyTest mt1 = String::substring; }} interface MyTest{/** * @param s String to be split * @param A starting position * @param b ending position * @return Returns the split String */ String test(String s, int a,int b); }Copy the code

4. Reference constructor

Public class Test {public static void main(String[] args) {public static void main(String[] args) {MyTest mt = a -> new JFrame(a); JFrame jf = mt.win(" This is my first Frame"); System.out.println(jf); // Use a constructor reference instead of a Lambda expression to create the object MyTest mt1 = JFrame::new; }} interface MyTest{/** * @param title name * @return JFrame type */ JFrame win(String title); }Copy the code