-
Enhancement
-
Resolution: Unresolved
-
P4
-
8
It is impossible to write the receiver parameter for a method of an anonymous class.
I expected this code to compile:
import java.util.Iterator;
public class AnonymousReceiver {
public Iterator<String> emptyIterator2() {
return new Iterator<String>() {
public boolean hasNext(Iterator<String> this) {
return false;
}
public String next(Iterator<String> this) {
throw new Error("No next element");
}
};
}
}
However, compiling it gives me error messages of the form
AnonymousReceiver.java:7: error: the receiver type does not match the enclosing class type
public boolean hasNext(Iterator<String> this) {
^
required: <anonymous Iterator<String>>
found: Iterator<String>
The javac error message is justified by Section 8.4.1 of the JLS, which says, "the type of the receiver parameter must be the class or interface in which the method is declared".
However, the JLS should permit writing a receiver formal parameter on an instance method of an anonymous class. In this case, the type of `this` would be required to be the direct superclass (the type named in the class instance creation expression).
The JLS special-cases the type of the receiver parameter in an inner class's constructor:
https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.1-410-B
However, it needs to also special-case the type of the receiver parameter in an anonymous class's instance methods:
https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.1-410-A
I expected this code to compile:
import java.util.Iterator;
public class AnonymousReceiver {
public Iterator<String> emptyIterator2() {
return new Iterator<String>() {
public boolean hasNext(Iterator<String> this) {
return false;
}
public String next(Iterator<String> this) {
throw new Error("No next element");
}
};
}
}
However, compiling it gives me error messages of the form
AnonymousReceiver.java:7: error: the receiver type does not match the enclosing class type
public boolean hasNext(Iterator<String> this) {
^
required: <anonymous Iterator<String>>
found: Iterator<String>
The javac error message is justified by Section 8.4.1 of the JLS, which says, "the type of the receiver parameter must be the class or interface in which the method is declared".
However, the JLS should permit writing a receiver formal parameter on an instance method of an anonymous class. In this case, the type of `this` would be required to be the direct superclass (the type named in the class instance creation expression).
The JLS special-cases the type of the receiver parameter in an inner class's constructor:
https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.1-410-B
However, it needs to also special-case the type of the receiver parameter in an anonymous class's instance methods:
https://docs.oracle.com/javase/specs/jls/se9/html/jls-8.html#jls-8.4.1-410-A
- relates to
-
JDK-8195646 Receiver parameter for a method of an anonymous class
-
- Open
-