Method reference_reference member method by object name

Refer to member method
by object name : Refer to member method by object name. The
premise is that the object name already exists and the member method already exists.
You can use the object name to refer to member method.
If a member method already exists in a class:

public class MethodRerObject {
    
    
    //定义一个成员方法,传递字符串,把字符串按照大写输出
    public void printUpperCaseString(String str){
    
    
        System.out.println(str.toUpperCase());
    }
}

The functional interface is defined as:

package Demo05.ObjectMethodReference;
/*
    定义一个打印的函数式接口
*/
@FunctionalInterface
public interface Printable {
    
    
    //定义字符串的抽象方法
    void print(String s);
}

Then when you need to use this printUpperCase member method to replace the Lambda of the Printable interface, and you already have an object instance of the MethodRefObject class, you can refer to the member method by the object name, the
code is:

public class Demo01ObjectMethodReference {
    
    
    //定义一个方法,方法的参数传递Printable接口
    public static void printString(Printable p){
    
    
        p.print("Hello");
    }

    public static void main(String[] args) {
    
    
        //调用printString方法,方法的参数是一个函数式接口,所以可以传递Lambda表达式
        printString((s)->{
    
    
            //创建MethodRerObject对象
            MethodRerObject obj = new MethodRerObject();
            //调用MethodRerObject对象中的成员方法printUpperCaseString,把字符串按照大写输出
            obj.printUpperCaseString(s);
        });

        /*
            使用方法引用优化Lambda
            对象是已经存在的MethodRerObject
            成员方法是已经存在的printUpperCaseString
            所以我们可以使用对象名引用成员方法
        */
        //创建MethodRerObject对象
        MethodRerObject obj = new MethodRerObject();
        printString(obj::printUpperCaseString);
    }
}

Program demonstration:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/109162517