方法引用主要是为了进一步简化Lambda表达式而生,采用的语法是双冒号 :: 写法,主要有以下几种情况:
通过对象名引用成员方法
public class Main {
public static void testA(InterfaceA a){
a.show();
}
public static void main(String[] args) {
//Lambda表达式写法
testA(()->{
ClassA c=new ClassA();
c.say();
});
//方法引用写法
ClassA c=new ClassA();
testA(c::say);
}
}
@FunctionalInterface
interface InterfaceA{
void show();
}
class ClassA{
public void say(){
System.out.println("哈哈");
}
}
通过类名引用静态方法
//输出一个数的绝对值
public class Main {
public static int testA(int x,InterfaceA a){
return a.transform(x);
}
public static void main(String[] args) {
//Lambda表达式写法
int result1 = testA(-10,a->Math.abs(a));
//方法引用写法
int result2 =testA(-10, Math::abs);
}
}
@FunctionalInterface
interface InterfaceA{
int transform(int a);
}
通过super引用父类成员方法
public class Main extends ClassA{
public void testA(InterfaceA a){
a.show();
}
public void testB(){
//Lambda表达式写法
testA(()->new ClassA().say());
testA(()->super.say());
//方法引用写法
testA(super::say);
}
}
class ClassA{
public void say(){
System.out.println("哈哈");
}
}
@FunctionalInterface
interface InterfaceA{
void show();
}
通过this引用本类成员方法
public class Main{
public void say(){
System.out.println("哈哈");
}
public void testA(InterfaceA a){
a.show();
}
public void testB(){
//Lambda表达式写法
testA(()->say());
testA(()->this.say());
//方法引用写法
testA(this::say);
}
}
@FunctionalInterface
interface InterfaceA{
void show();
}
类的构造器引用
public class Main{
public Person testA(String name,InterfaceA a){
return a.A(name);
}
public void testB(){
//Lambda表达式写法
testA("xiaoming",(name)->new Person(name));
//方法引用写法
testA("xiaohong",Person::new);
}
}
@FunctionalInterface
interface InterfaceA{
Person A(String name);
}
class Person{
private String name;
public Person(){}
public Person(String name){
this.name=name;
}
}
数组的构造器引用
public class Main{
public int[] testA(int len,InterfaceA a){
return a.A(len);
}
public void testB(){
//Lambda表达式写法
testA(10,(len)->new int[len]);
//方法引用写法
testA(10, int[]::new);
}
}
@FunctionalInterface
interface InterfaceA{
int[] A(int len);
}
静态方法不能调用非静态方法,并且还不能有this、super关键字
由于在前面举例的时候,在静态方法里面使用了super关键字,导致编译出错,是因为遗忘了静态方法里面不能有super关键字的细节,因此在这里进行总结补充:
- 静态方法不能调用非静态方法,并且还不能有this、super关键字
解释:因为this代表的是调用这个函数的对象的引用,而静态方法是属于类的,不属于对象,静态方法成功加载后,对象还不一定存在;super的用法跟this类似,super代表对父类对象的引用,指向父类对象,同样静态方法成功加载后,父类对象还不一定存在。
2. 非静态方法可以调用静态方法也可以调用非静态方法,并且方法内可以使用this、super关键字
关于jdk1.8的其它新特性:
- jdk1.8新特性——Optional类:https://blog.csdn.net/can_chen/article/details/106886579
- jdk1.8新特性——Stream流式编程:https://blog.csdn.net/can_chen/article/details/106886484
- jdk1.8新特性——Lambda表达式与函数式接口:https://blog.csdn.net/can_chen/article/details/106886385