方法引用是lambda表达式中引用方法而不执行该方法的方法。在lambda表达式的主体中,如果它们与功能接口兼容,则可以调用另一个方法。
运算符 “ ::”可用于将类名与方法名分开。
使用类名引用了静态方法。在 lambda 表达式中,我们可以使用以下语法引用静态方法。
Class-name :: Method-name;
interface Test { void func(); } class StaticMethodRef { static void message() { System.out.println("Welcome to www.nhooo.com"); } } public class LambdaMethodRefTest1 { public static void main(String arg[]) { Test test = StaticMethodRef :: message; //使用“ ::”运算符调用 test.func(); } }
输出结果
Welcome to www.nhooo.com
通过使用lambda表达式来引用实例方法。 我们需要引用一个实例方法,使用实例名称而不是类名称。 “ ::”运算符还可用于引用实例方法。
Instance-name :: Method-name;
interface Test { void func(); } class InstanceMethodRef { void message() { System.out.println("Welcome to www.nhooo.com"); } } public class LambdaMethodRefTest2 { public static void main(String arg[]) { InstanceMethodRef ref = new InstanceMethodRef(); Test test = ref :: message; //使用“ ::”运算符调用 test.func(); } }
输出结果
Welcome to www.nhooo.com