1
public enum FOO{
    TATA(TOTO,TITI);

    public FOO(BAR bar1,BAR bar2) {
        bar1.associate(this,bar2);
    }
}

public enum BAR {
    TOTO,
    TITI;

    private FOO _foo;
    private BAR _bar;

    public void associate(FOO foo,BAR bar) {
        _foo = foo;
        _bar = bar;
    }
}

The problem was that in my code I called BAR before FOO. The result was the fields in BAR were null. I finally found out why. (enum are only instantiated when they are called for the first time). To fix this problem I added FOO.TATA; before I use Bar in a specific file.

So my question, Is there a more elegant way to make sure one enum is instantiate before another?

2
  • 3
    What do these enum represent in real life? It seems it's not very good place to use enums. Commented May 29, 2012 at 16:39
  • @NikitaBeloglazov it being use in a factory.. and unfortunately I don't have my word to say on this matter. Commented May 29, 2012 at 16:43

1 Answer 1

2

Since they're closely related to each other, I would put them in the same class, that would play the role of a mediator:

public class FooBar {
    static {
        Bar.TOTO.associate(Foo.TATA, Bar.TITI);
    }

    public enum Foo {
        TATA;
    }

    public enum Bar {
        TOTO,
        TITI;

        private Foo _foo;
        private Bar _bar;

        private void associate(Foo foo, Bar bar) {
            _foo = foo;
            _bar = bar;
        }

        public Foo getFoo() {
            return _foo;
        }

        public Bar getBar() {
            return _bar;
        }
    }

    public static void main(String[] args) {
        System.out.println(FooBar.Bar.TITI.getFoo());
        System.out.println(FooBar.Bar.TITI.getBar());
        System.out.println(FooBar.Bar.TOTO.getFoo());
        System.out.println(FooBar.Bar.TOTO.getBar());
    } 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, It's not exactly what I've done but I give me good idea !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.