Java Method References

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference. In this tutorial, we are explaining method reference concept in detail.

函数接口是只有一个抽象方法的接口,用作 Lambda 表达式的类型。
所以,接口Sayable中,是啥方法名无所谓,但是一定是只有一个方法。

Types of Method References

There are following types of method references in java:

  1. Reference to a static method.
  2. Reference to an instance method.
  3. Reference to a constructor.

1) Reference to a Static Method

You can refer to static method defined in the class. Following is the syntax and example which describe the process of referring static method in Java.

Syntax

ContainingClass::staticMethodName

Example 1

In the following example, we have defined a functional interface and referring a static method to it’s functional method say().

interface Sayable{  
    void say();  
}  
public class MethodReference {  
    public static void saySomething(){  
        System.out.println("Hello, this is static method.");  
    }  
    public static void main(String[] args) {  
        // Referring static method  
        Sayable sayable = MethodReference::saySomething;  
        // Calling interface method  
        sayable.say();  
    }  
}  

Test it Now

Output:

Hello, this is static method.

Example 2

In the following example, we are using predefined functional interface Runnable to refer static method.

public class MethodReference2 {  
    public static void ThreadStatus(){  
        System.out.println("Thread is running...");  
    }  
    public static void main(String[] args) {  
        Thread t2=new Thread(MethodReference2::ThreadStatus);  
        t2.start();       
    }  
}  

Test it Now

Output:

Thread is running...

java 结束main_为什么java main主线程退出了子线程还能运行;golang main结束所有协程都被结束了…

最近看golang main函数结束,所有协程都被结束了

结论是这样:A不是main程的情况下,在A程里开启B程,A程执行完,A程return之后,B程不受影响,不会挂掉。所有子协程与main程同级的,与main程伴生

java主线程结束和子线程结束之间的关系

Main线程是个非守护线程,不能设置成守护线程。

这是因为,main线程是由java虚拟机在启动的时候创建的。main方法开始执行的时

候,主线程已经创建好并在运行了。对于运行中的线程,调用Thread.setDaemon(true)会

抛出异常Exception in thread “main” java.lang.IllegalThreadStateException。

Main线程结束,其他线程一样可以正常运行

主线程,只是个普通的非守护线程,用来启动应用程序,不能设置成守护线程;除此之外,它跟其他非守护线程没有什么不同。主线程执行结束,其他线程一样可以正常执行

Main线程结束,其他线程也可以立刻结束,当且仅当这些子线程都是守护线程。

java虚拟机(相当于进程)退出的时机是:虚拟机中所有存活的线程都是守护线程。只要还有存活的非守护线程虚拟机就不会退出,而是等待非守护线程执行完毕;反之,如果虚拟机中的线程都是守护线程,那么不管这些线程的死活java虚拟机都会退出


Example 3

You can also use predefined functional interface to refer methods. In the following example, we are using BiFunction interface and using it’s apply() method.

import java.util.function.BiFunction;  
class Arithmetic{  
    public static int add(int a, int b){  
        return a+b;  
    }  
}  
public class MethodReference3 {  
    public static void main(String[] args) {  
        BiFunction<Integer, Integer, Integer>adder = Arithmetic::add;  
        int result = adder.apply(10, 20);  
        System.out.println(result);  
    }  
}  

Test it Now

Output:

30

Example 4

You can also override static methods by referring methods. In the following example, we have defined and overloaded three add methods.

import java.util.function.BiFunction;  
class Arithmetic{  
    public static int add(int a, int b){  
        return a+b;  
    }  
    public static float add(int a, float b){  
        return a+b;  
    }  
    public static float add(float a, float b){  
        return a+b;  
    }  
}  
public class MethodReference4 {  
    public static void main(String[] args) {  
        BiFunction<Integer, Integer, Integer>adder1 = Arithmetic::add;  
        BiFunction<Integer, Float, Float>adder2 = Arithmetic::add;  
        BiFunction<Float, Float, Float>adder3 = Arithmetic::add;  
        int result1 = adder1.apply(10, 20);  
        float result2 = adder2.apply(10, 20.0f);  
        float result3 = adder3.apply(10.0f, 20.0f);  
        System.out.println(result1);  
        System.out.println(result2);  
        System.out.println(result3);  
    }  
}  

Test it Now

Output:

30
30.0
30.0

2) Reference to an Instance Method

like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

containingObject::instanceMethodName 

Example 1

In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object.

interface Sayable{  
    void say();  
}  
public class InstanceMethodReference {  
    public void saySomething(){  
        System.out.println("Hello, this is non-static method.");  
    }  
    public static void main(String[] args) {  
        InstanceMethodReference methodReference = new InstanceMethodReference(); // Creating object  
        // Referring non-static method using reference  
            Sayable sayable = methodReference::saySomething;  
        // Calling interface method  
            sayable.say();  
            // Referring non-static method using anonymous object  
            Sayable sayable2 = new InstanceMethodReference()::saySomething; // You can use anonymous object also  
            // Calling interface method  
            sayable2.say();  
    }  
}  

Test it Now

Output:

Hello, this is non-static method.
Hello, this is non-static method.

Example 2

In the following example, we are referring instance (non-static) method. Runnable interface contains only one abstract method. So, we can use it as functional interface.

public class InstanceMethodReference2 {  
    public void printnMsg(){  
        System.out.println("Hello, this is instance method");  
    }  
    public static void main(String[] args) {  
    Thread t2=new Thread(new InstanceMethodReference2()::printnMsg);  
        t2.start();       
    }  
}

Test it Now

Output:

Hello, this is instance method

Example 3

In the following example, we are using BiFunction interface. It is a predefined interface and contains a functional method apply(). Here, we are referring add method to apply method.

import java.util.function.BiFunction;
class Arithmetic{
    public int add(int a, int b){
        return a+b;
    }
}
public class InstanceMethodReference3 {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer>adder = new Arithmetic()::add;
        int result = adder.apply(10, 20);
        System.out.println(result);
    }
}

Test it Now

Output:

30

3) Reference to a Constructor

You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.

Syntax

ClassName::new

Example

interface Messageable{  
    Message getMessage(String msg);  
}  
class Message{  
    Message(String msg){  
        System.out.print(msg);  
    }  
}  
public class ConstructorReference {  
    public static void main(String[] args) {  
        Messageable hello = Message::new;  
        hello.getMessage("Hello");  
    }  
}  

Test it Now

Output:

Hello

参考文章
1、https://www.javatpoint.com/java-8-method-reference

猜你喜欢

转载自blog.csdn.net/yangyangrenren/article/details/121184327