非常常见的初学者错误是当您尝试"静态"使用类属性而不创建该类的实例时.它会留下您提到的错误消息:
您可以将非静态方法设为静态,也可以使该类的实例使用其属性.
为什么?我不是要求解决方案.我很高兴知道它背后的原因是什么.核心原因!
private java.util.List<String> someMethod(){
/* Some Code */
return someList;
}
public static void main(String[] strArgs){
// The following statement causes the error. You know why..
java.util.List<String> someList = someMethod();
}
Run Code Online (Sandbox Code Playgroud) 假设我有一个Pair类
public class Pair<P, Q> {
public P p;
public Q q;
public Pair(P p, Q q) {
this.p = p;
this.q = q;
}
public int firstValue() {
return ((Number)p).intValue();
}
public int secondValue() {
return ((Number)q).intValue();
}
}
Run Code Online (Sandbox Code Playgroud)
我希望对它进行排序,首先是第一个值,然后是第二个值.现在'如果我这样做
List<Pair<Integer, Integer>> pairList = new ArrayList<>();
pairList.add(new Pair<>(1, 5));
pairList.add(new Pair<>(2, 2));
pairList.add(new Pair<>(2, 22));
pairList.add(new Pair<>(1, 22));
pairList.sort(Comparator.comparing(Pair::firstValue));
Run Code Online (Sandbox Code Playgroud)
一切都运行良好,列表按对的第一个值排序,但如果我这样做
pairList.sort(Comparator.comparing(Pair::firstValue).thenComparing(Pair::secondValue));
Run Code Online (Sandbox Code Playgroud)
它失败了,错误
Error:(24, 38) java: incompatible types: cannot infer type-variable(s) T,U
(argument mismatch; invalid method reference
method firstValue in …Run Code Online (Sandbox Code Playgroud) 我有一个学生列表,我想将其转换为Map<String, Integer>,其中映射键应该是学生的名字。为了保持代码示例简单,我将映射值指定为1:
final Map<String, Integer> map = someStudents.stream().collect(
Collectors.toMap(Student::getFirstName, 1));
Run Code Online (Sandbox Code Playgroud)
编译器抱怨:
不能从静态上下文中引用非静态方法 getFirstName()
任何的想法?我很困惑,因为许多示例使用相同的方法传递对非静态方法的引用。为什么编译器会在这里看到静态上下文?