我们如何在 Java 中的方法引用中使用 this 和 super 关键字?
方法引用类似于一个lambda 表达式,它引用方法而不会执行它,并且 "::" 运算符可以用来分隔方法引用中方法名与对象或类名。
可以在 Java 中借助 this 和 super 关键字 来引用方法。super 关键字可以用作限定符,以在类或接口中调用重写的方法。
语法
this::instanceMethod TypeName.super::instanceMethod
示例
import java.util.function.Function;
interface Defaults {
default int doMath(int a) {
return 2 * a;
}
}
public class Calculator implements Defaults {
@Override
public int doMath(int a) {
return a * a;
}
public void test(int value) {
Function<Integer, Integer> operator1 = this::doMath;
System.out.println("this::doMath() = " + operator1.apply(value));
Function<Integer, Integer> operator2 = Defaults.super::doMath;
System.out.println("Defaults.super::doMath() = " + operator2.apply(value));
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.test(10);
}
}输出
this::doMath() = 100 Defaults.super::doMath() = 20
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP