0

I have two classes, Outer and Inner, and a method in Outer that takes an Inner. It needs to validate that this Inner is one of its own, and not an Inner that belongs to another instance. What I'd like to do is essentially innerInstance.outer.this, but there doesn't seem to be a keyword for that. My only other idea is a getOuterThis() method on Inner, but I'd rather not have to resort to that.

Here's the general skeleton of what I'm trying to accomplish:

public class Outer {

    public Inner getInner() { ... }

    public void useInner(Inner inner) {
        // Validate here
    }

    public class Inner {
        // Can I avoid this?
        public Outer getOuterThis() {
            return Outer.this;
        }
    }
}
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
  • @EJP The Eclipse compiler didn't like it. And this is a different question from the duplicate you linked. This is how to do it from the outer class without adding a method to the inner class. The answer there was clearly just Outer.this. – David Ehrmann Jul 27 '14 at 02:16

1 Answers1

1

I don't think there's a good way to get the Outer.this reference except by explicitly exposing it like you're doing. However, you can probably avoid this altogether by having the inner class do the validation:

public class Outer {

    public Inner getInner() { ... }

    public void useInner(Inner inner) {
        // Validate
        inner.validateOuterInstance(this);
    }

    public class Inner {
        public void validateOuterInstance(Outer outer) {
            if (Outer.this != outer) {
                throw new InvalidArgumentException("Wrong outer instance");
            }
        }
    }
}
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
DaoWen
  • 32,589
  • 6
  • 74
  • 101