Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8195645

8.4.1: Allow receiver parameter for a method of an anonymous class

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • tbd
    • 8
    • specification

      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

            abuckley Alex Buckley
            mernst Michael Ernst (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: