The code is valid in Eclipse, cannot be compiled by JDK

I experience an interesting mismatch between what Eclipse and my JDK consider legal java.

Eclipse compiles the following class without crashing, while the JDK on Mac OS X results in the error below.

public class Builder { private class Item {} public void addItem(Item i) {} public static void main(String[] args) { new Builder() {{ addItem(new Item()); }}; } } 

 $ javac Builder.java Builder.java:9: non-static variable this cannot be referenced from a static context addItem(new Item()); ^ 1 error 

Creating a static Item class fixes the problem, but I was a little curious: Is Eclipse soft and compiles code that is not really valid? Am I stumbled upon the eccentricity of the Mac OS X JDK? Am I missing something?

Update It may be appropriate to include the following

 $ java -version java version "1.6.0_33" Java(TM) SE Runtime Environment (build 1.6.0_33-b03-424-11M3720) Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode) 

Update 2

Making the element more visible (by default, protected or public) also satisfies the JDK compiler.

+4
source share
5 answers

javac 1.7.0_04 compiles the source without errors, so I would suggest that this is a bug in javac 1.6.

+4
source

I get the same result, but interestingly changing the code to:

 new Builder() {{ addItem(this.new Item()); }}; 

(which should be identical) raises another error message:

 Builder.java:9: Builder.Item has private access in Builder addItem(this.new Item()); 

I suspect this is a real basic mistake - the Item class is private, so it does not appear in an anonymous subclass. Changing Item to protect rather than private allows both the original version and the version of this.new compile successfully.

+2
source

In Eclipse, by default, Access to a non-accessible member of an enclosing type can be ignored by default. If you go to Project-> Properties-> Java Compiler-> Errors / Warning, you can enable specific project settings.

The discrepancy is probably due to the fact that Eclipse comes with its own compiler - part of the JDT , which is slightly different from javac .

+1
source

I think this is a bug in the eclipse compiler. The inner class of Item is not static, so you can only access it through the Builder object, for example:

new Builder().new Item()

By initializing the Item class in a static block, you do not have an instance of Builder, so this code that you posted should not work. Very interesting mistake.

0
source

Add static to an element class declaration, for example static class Item {}

-2
source

All Articles