java 使用函数式接口的疑问
为什么第一个第一次调用functionTest方法时提示Non-static method cannot be referenced from a static context
为什么不能这么使用,第二次调用functionTest方法为什么没有报错,有没有大概详细解释一下,这一块不太懂。。
以下是全部代码
public class FunctionTest1 {
public static void main(String[] args) {
List<UserInfo> userInfoList = getUserList();
userInfoList.forEach(obj -> {
//提示Non-static method cannot be referenced from a static context
functionTest(obj, UserInfo::setNameDescTest);
//不报错
functionTest(obj, obj::setNameDescTest);
//不报错
functionTest1(obj, UserInfo::getNameDesc);
});
}
public static void functionTest(UserInfo userInfo, Function<String, Boolean> function) {
Boolean apply = function.apply(userInfo.toString());
System.out.println(apply);
}
public static void functionTest1(UserInfo userInfo, Function<UserInfo, String> function) {
String apply = function.apply(userInfo);
System.out.println(apply);
}
public static List<UserInfo> getUserList() {
List<UserInfo> userInfoList = new ArrayList<>();
UserInfo userInfo = new UserInfo();
UserInfo userInfo1 = new UserInfo();
userInfoList.add(userInfo);
userInfoList.add(userInfo1);
return userInfoList;
}
}
public class UserInfo {
private int age;
private String name;
private Double money;
private String nameDesc;
public UserInfo() {
}
public UserInfo(int age, String name, Double money) {
this.age = age;
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "UserInfo{" +
"age=" + age +
", name='" + name + '\'' +
", money=" + money +
", nameDesc='" + nameDesc + '\'' +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public static void testStatic() {
System.out.println("testStatic....");
}
public String getNameDesc() {
this.name = "545tr";
return nameDesc;
}
public boolean setNameDescTest(String nameDesc) {
//this.nameDesc = nameDesc;
System.out.println(nameDesc);
return true;
}
public void setNameDesc(String nameDesc) {
this.nameDesc = nameDesc;
}
}