给定以下代码:
package com.gmail.oksandum.test;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
}
public void foo() {
class LocalFoo {
LocalFoo(String in) {
//Some logic
}
}
List<String> ls = new ArrayList<>();
ls.stream().map(LocalFoo::new); //Line 21
}
}
我的 IDE 没有给我任何错误。也就是说,直到我尝试构建项目并运行它。当我这样做时,它会给我一个编译器错误,如下所示:
Error:(21, 24) java: incompatible types: cannot infer type-variable(s) R
(argument mismatch; invalid constructor reference
cannot access constructor LocalFoo(java.lang.String)
an enclosing instance of type com.gmail.oksandum.test.Test is not in scope)
现在,我认为,鉴于错误消息,如果 foo() 是静态的,则不会发生这种情况。非常正确,只有当 foo() 是一个实例方法时才会发生这种情况。只有当 LocalFoo 是实例方法中的本地类时,才会发生这种情况,并且只有在使用构造函数引用(即从不使用常规方法引用)时才会发生。
更重要的是,如果我将第 21 行更改为
ls.stream().map(str -> new LocalFoo(str));
编译器突然没有错误。
所以回顾一下。如果我尝试在实例方法中声明的本地类上使用构造函数引用,编译器会抱怨无法访问构造函数,对此我感到困惑。
如果有人可以阐明为什么会发生这种情况,将不胜感激。谢谢。