:: 该符号为引用运算符,而它所在的表达式被称为方法引用
引用对象的实例方法,其实就引用类中的成员方法
格式
对象::成员方法
1.接口
public interface Duixiang {
public String toUpper(String str);
}
2.定义一个转换大小写的类
public class Zhuan {
public String toZhuan(String str){
return str.toUpperCase();
}
}
3.测试结果:
- public class TestDuixiang {
- public static void main(String[] args) {
- //lamda表达式
- Duixiang duixiang=(x)->{return x.toUpperCase();};
- String k= duixiang.toUpper("ssss");
- System.out.println("k:"+k);
- //实例2
- Zhuan z=new Zhuan();
- Duixiang duixiang1=z::toZhuan;
- String t=duixiang1.toUpper("abcdd");
- System.out.println("t:"+t);
- }
- }

1.接口
public interface H {
public int H(String x);
}
2.调用
- public class TestLei {
- public static void main(String[] args) {
- H m=(x)->{return Integer.parseInt(x); };
- int n=m.H("5");
- System.out.println("n:"+n);
- //方式2
- H h= Integer::parseInt;
- int k= h.H("5");
- System.out.println("k:"+k);
- }
- }
3.调用结果

引用类的实例方法,其实就是引用类中的成员方法
格式
类名::成员方法
1接口
public interface LeiMethod {
public String getSubString(String str,int x,int y);
}
2.调用类
- public class TestLeiMethod {
- public static void main(String[] args) {
- //方式1
- LeiMethod lm=(String x,int m,int n)->{return x.substring(m,n);};
- String s=lm.getSubString("qwertrrereeew",0,4);
- //
- String ss=get("qwertrrereeew",String::substring);
- System.out.println("ss:"+ss);
-
- }
- public static String get(String str,LeiMethod lm){
- return lm.getSubString(str,0,4);
- }
- }
3.结果

引用构造器,其实就是引用构造方法
l格式
类名::new
1.接口
public interface Gou {
public Teacher getTeacher(String name,int age);
}
2.调用
- package diaoyong;
-
- /**
- * @ClassName: TestTeacher
- * @Description: TODO
- * @Author: liujianfu
- * @Date: 2022/11/06 16:59:51
- * @Version: V1.0
- **/
- public class TestTeacher {
- public static void main(String[] args) {
- Gou g=(String name,int age)->{return new Teacher(name,age);};
- Teacher t= g.getTeacher("asdfas",45);
- System.out.println("name:"+t.getName()+" age"+t.getAge());
- //方式2
- Teacher tt= get(Teacher::new);
- System.out.println("name:"+tt.getName()+" age"+tt.getAge());
- //方式3
- Gou gg=Teacher::new;
- Teacher c= gg.getTeacher("adfa",456);
- System.out.println("name:"+c.getName()+" age"+c.getAge());
- }
- public static Teacher get(Gou g){
- Teacher t= g.getTeacher("ass",40);
- return t;
- }
- }
3.结果
