package com.example.demo;
/**
* @author shenqingwen
* @date 2020/10/15
*/
public class StudentTest {
private String name;
private Integer score;
//该方法将要注入到函数式接口TestInterface中
public void setNameAndScore(String name, Integer score)
{
this.name = name;
this.score = score;
System.out.println("Student "+ name +"'s score is " + score);
}
public static void main(String[] args)
{
//1.匿名类方式:
// TestInterface testInterface = new TestInterface(){
// public void set(StudentTest d, String name, Integer score){
// d.setNameAndScore(name, score);
// }
// };
//2.lambda表达式的用法:
// TestInterface testInterface = (studentTest, name, score) -> studentTest.setNameAndScore(name, score);
//java8方法引用有四种形式:静态方法引用; 构造器引用; 类的任意对象的实例方法引用; 特定对象的实例方法引用;
//3.类的 任意对象 的实例方法引用的用法:类的任意对象的实例方法引用的语法格式为: 类名::实例方法名
TestInterface testInterface = StudentTest::setNameAndScore;
testInterface.set(new StudentTest(), "Alex", 100);
}
//表明是函数式接口的注释
@FunctionalInterface
interface TestInterface
{
// 注意:入参比Student类的setNameAndScore方法多1个Student对象,除第一个外其它入参类型一致
public void set(StudentTest d, String name, Integer score);
}
}
与下篇博客:https://blog.csdn.net/qq_16494249/article/details/109110196
中代码进行对比,可帮助理解 类的任意对象的实例方法引用 与 特定对象的实例方法引用 两者间的区别: