Skip to content
Advertisement

Why enum constructor “this” and “Enum.this” is different

I have a local enum cache, need in enum constructor return enum instance. but when return ‘this’ , it’s fail, return ‘Enum.this’ , it’s ok. the exception looks like a inner class. because this instance is not finish ? this is my code and exception

JavaScript
JavaScript
JavaScript

enter image description here

enter image description here

Advertisement

Answer

Here:

JavaScript

Notice that the get method is inside of an anonymous inner class new EnumGetter() { ... }. This creates a class like this.

JavaScript

Imagine this code being placed inside of TestEnum. So inside of get, the unqualified word this refers to the current instance of SomeAnonymousClassName, rather than the instance of the enum.

As the Java Language Specification says:

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked, or to the object being constructed.

To refer to the current instance of the enum, you have to use TestEnum.this.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement