Java静态上下文匿名类访问非静态字段编译报错咨询
问题分析:静态上下文与匿名内部类的变量访问问题
示例代码
public class DataStructure { // Create an array private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { // fill the array with ascending integer values for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void print(DataStructureIterator iter) { while(iter.hasNext()) { System.out.print(iter.next() + " "); } System.out.println(); } interface DataStructureIterator extends java.util.Iterator<Integer> { } // Inner class implements the DataStructureIterator interface, // which extends the Iterator<Integer> interface private class EvenIterator implements DataStructureIterator { // Start stepping through the array from the beginning private int nextIndex = 0; public boolean hasNext() { // Check if the current element is the last in the array return (nextIndex <= SIZE - 1); } public Integer next() { // Record a value of an even index of the array Integer retValue = Integer.valueOf(arrayOfInts[nextIndex]); // Get the next even element nextIndex += 2; return retValue; } } public static void main(String s[]) { // Fill the array with integer values and print out only // values of even indices DataStructure ds = new DataStructure(); ds.print( new DataStructure.DataStructureIterator() { private int nextIndex = 1; public boolean hasNext() { return (nextIndex <= ds.size() - 1); } public Integer next() { //int retValue = arrayOfInts[nextIndex]; // this won't work: // non-static variable arrayOfInts cannot be referenced from a static context int retValue = ds.get(nextIndex); nextIndex += 2; return retValue; } } ); } }
编译错误
error: non-static variable arrayOfInts cannot be referenced from a static context
核心问题
我理解静态上下文无法访问非静态变量,这完全合理。但在此场景中,我并非直接在静态上下文中访问该变量,而是将一段代码(匿名类)传给非静态方法。非静态方法显然可以访问非静态变量,为何此处无法直接访问?
解答
关键在于匿名内部类的上下文归属由定义位置决定,而非执行位置:
- 你在
main方法(静态上下文)中定义的匿名类,其作用域属于静态方法,创建时不会自动持有外部类DataStructure的实例引用,因此受静态上下文规则限制,不能直接访问非静态成员arrayOfInts。 - 对比代码中的
EvenIterator类:它是非静态内部类,默认持有外部类实例的引用,所以能直接访问arrayOfInts。但静态方法内的匿名类不具备这个特性。 - 你通过
ds.get(nextIndex)能正常访问,是因为显式引用了ds这个具体的外部类实例,而非直接访问类的非静态成员。
内容的提问来源于stack exchange,提问作者YoavKlein
相关产品推荐
相关产品推荐

