五月十六号java基础知识点
阅读原文时间:2023年07月09日阅读:1

1.方法引用就是用双冒号“::”来简化Lambda表达式
2.方法引用四种引用方式:
1)对象名::实例方法名 //用对象名调用实例方法
2)类名::静态方法名 //用类名引用静态方法

@FunctionalInterface
interface StringFunc{
public String func(String s);
}
public class app13_9 {
//定义静态方法sop
static String sop(StringFunc sf,String s){
return sf.func(s);//是函数式接口类型
}
public static void main(String[] args) {//Lambda表达式作为参数传递给方法
//先定义字符型变量instr以及outstr,并输出原字符
String outstr,instr = "Lambda 表达式 good";
System.out.println("原字符串:"+instr);
//将字符串instr转换成大写赋值给outstr
outstr = sop((str)->str.toUpperCase(),instr);
System.out.println("转换成大写字母后:"+outstr);
//将字符串去掉空格后
outstr = sop((str)->{
String result = "";
for (int i = 0; i {
String result ="";
for (int i = str.length()-1; i >=0 ; i--) {
result+=str.charAt(i);
}
return result;
};
System.out.println("反序后字符串:"+sop(reverse,instr));
}
}

3)类名::实例方法名 //用类名引用实例方法名
第一个参数作为方法调用者,其他参数传递给方法
字符串1.compareTo(字符串2)
str1::compareTo等价于(str1,str2)->str1.compareTo(str2);
4)类名::new //用类名引用构造方法
可把构造按方法引用赋值给与构造方法具有相同相同方法头的任何函数式接口对象

@FunctionalInterface
interface IShow{
public T create(String s,int n);
}
class Persons{
String name;
int age;
public Persons(){
name = "刘洋";
age = 24;
}
public Persons(String n,int a){
this.name = n;
this.age = a;
}
@Deprecated
public String toString(){
return "姓名:"+this.name+",年龄:"+this.age;
}
}
public class app13_11 {
public static void main(String[] args) {
IShow na = Persons::new;//创建Persons构造方法的引用
Persons p = na.create("陈磊",23);//调用create()方法,但引用Persons构造方法
System.out.println(p);
}
}

3.注意:被引用方法参数列表和返回值类型,必须与函数式接口中的抽象方法参数列表和返回值类型
一致
4.说明:前三种方法引用::右边的方法名后不能有括号,第四种::后面只能是关键字
5.前两种只用于只有一个参数情况,方法等同于Lambda表达式
例如:System.out::print等同于System.out.println(s);
第三种用于两个及以上,第一个参数是调用方法对象

@FunctionalInterface
interface Ishow{
//抽象方法info()的方法头与引用方法valueOf()的方法头有相同定义,方法info()的,名字就是方法引用的名字
public R info(P p);
}
public class app13_10 {
public static void main(String[] args) {
Ishow ip = String::valueOf;//用类名String引用静态方法valueOf
String s = ip.info(886);//调用方法info相当于调用valueOf方法
System.out.println(s);
}
}

6.三种方式实现函数式接口Comsumer,接口中包含一个抽象方法void accept(T t).
1)Comsumer con = new Comsumer
{
@Override
public void accept(String str){
System.out.println(str)}
};
con.accept("我是一个消费型接口");
2)Lambda表达式
Comsumer con = str->System.out.println(str);
con.accept("我是一个消费接口");
3)方法引用
Comsumer con =System.out::println
con.accept("我是一个消费接口")

总结:学习了四种方法引用

第一种:对象名::实例方法名

第二种:类名::静态方法名

第三种:类名::实例方法名

第四种:类名::new//类名引用构造方法

前两种中只有有一个参数,等同于Lambda表达式

//抽象方法info()的方法头与引用方法valueOf()的方法头有相同定义,方法info()的,名字就是方法引用的名字
public R info(P p);
着个语句没有理解,方法头是什么,并且为什么可以直接引用valueOf()函数
方法头指的是public R,R是泛型指方法的类型

IShow na = Persons::new;//创建Persons构造方法的引用

类名::new构造方法引用赋值给Person类属性的接口类实现对象

Persons p = na.create("陈磊",23);//调用create()方法,但引用Persons构造方法

调用接口中的create()方法,但是却在定义Person类对象时调用了构造方法