Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

java - How to refer to the outer class in another instance of a non-static inner class?

I'm using the Apache Commons EqualsBuilder to build the equals method for a non-static Java inner class. For example:

import org.apache.commons.lang.builder.EqualsBuilder;

public class Foo {
    public class Bar {
        private Bar() {}

        public Foo getMyFoo() {
            return Foo.this
        }

        private int myInt = 0;

        public boolean equals(Object o) {
            if (o == null || o.getClass() != getClass) return false;

            Bar other = (Bar) o;
            return new EqualsBuilder()
                .append(getMyFoo(), other.getMyFoo())
                .append(myInt, other.myInt)
                .isEquals();
        }
    }

    public Bar createBar(...) {
        //sensible implementation
    }

    public Bar createOtherBar(...) {
        //another implementation
    }

    public boolean equals(Object o) {
        //sensible equals implementation
    }
}

Is there syntax by which I can refer to other's Foo reference apart from declaring the getMyFoo() method? Something like other.Foo.this (which doesn't work)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No.

The best way is probably what you suggested: add a getFoo() method to your inner class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...