2

SSCCE:

public class Test {
    public Test() {
        new Anonymous1() {
            void validate() {
                new Anonymous2() {
                    int calculate() {
                        return Math.abs(Anonymous1.this.getValue()); // compilation error - Anonymous1 is not an enclosing class
                    }
                };
            }
        };
    }
}

abstract class Anonymous1 {
    abstract void validate();

    int getValue() {
        return 0;
    }
}

abstract class Anonymous2 {
    abstract int calculate();
}

I know that it looks complicated and unusable, but I am just wonder is it possible to point to Anonymous1 class from Anonymous2 using .this pointer, or in any else way.

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
SeniorJD
  • 6,946
  • 4
  • 36
  • 53
  • @SeniorJD not totally fixed classes definition... – Luigi Cortese Mar 11 '16 at 08:29
  • 1
    The problem is, `Anonymous1` and `Anonymous2` are not the names of those inner classes. `Anonymous1` and `Anonymous2` are the *superclasses* of those inner classes. You need to use the actual name of the class for `Something.this`, but there is no name because they are anonymous. – newacct Mar 15 '16 at 00:48

1 Answers1

4

You need to do it in the class.

public Test() {
    new Anonymous1() {
        void validate() {
            final Object this1 = this;
            new Anonymous2() {
                int calculate() {
                    return Math.abs(this1.getValue()); 
                }
            }
        }
    }
}

or even better, extract the things you need first and use effectively final added in Java 8.

public Test() {
    new Anonymous1() {
        void validate() {
            int value = getValue();
            new Anonymous2() {
                int calculate() {
                    return Math.abs(value); 
                }
            }
        }
    }
}

if Anonymous1 and Anonymous2 were interfaces you could use lambdas in Java 8.

public Test() {
   Anonymous1 a = () -> {
      int v = getValue();
      Anonymous2 = a2 = () -> Math.abs(v);
   };

}

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130