LastStar007
LastStar007

Reputation: 765

Java reference inner enum without enum name

I have a Java class with a 2-option enum inside of it. The outer class has a member instance of the enum. I have a method that switches the member's option. Like so:

    public class Foo {
        public enum BarEnum {
            OPTION1, OPTION2;
        }

        private BarEnum barmember;

        private void switchBarmember {
            switch (barmember) {
                case OPTION1: barmember = BarEnum.OPTION2; break;
                case OPTION2: barmember = BarEnum.OPTION1; break;

            }
        }
    }

My question is, is there a way to execute the change without saying BarEnum.? In other words, is there a way to make the method look like this:

        private void switchBarmember {
            switch (barmember) {
                case OPTION1: barmember = OPTION2; break;
                case OPTION2: barmember = OPTION1; break;

            }
        }

If there isn't a way, just let me know. Thanks!

Upvotes: 2

Views: 3318

Answers (3)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

Not exactly, but this will work:

public class Foo {
    public enum BarEnum {
        OPTION1,
        OPTION2;

        private BarEnum switchValue ( )
        {
            switch( this )
            {
            case OPTION1:
                 return OPTION2;
            case OPTION2:
                 return OPTION1;
            }

            throw new AssertionError("Should not be here");
        }
    }

    private BarEnum barmember;

    private void switchBarmember {
        barmember = barmember.switchValue( );
    }
}

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 44808

This is not possible unless you create new fields like @Pshemo did.

If this enum was in a separate file, it would be possible to statically import the enum constants to achieve this:

import static foo.TestEnum.ONE;
import foo.TestEnum;

public class StaticImportEnum {
    public static void main (String[] args) {
        TestEnum foo = ONE;
    }
}


package foo;

public enum TestEnum {
    ONE, TWO;
}

However, you should use static imports sparingly as they are generally considered bad practice.

Upvotes: 1

Pshemo
Pshemo

Reputation: 124225

Maybe this way :)

class Foo {
    public enum BarEnum {
        OPTION1, OPTION2;
    }
    private BarEnum OPTION1=BarEnum.OPTION1;
    private BarEnum OPTION2=BarEnum.OPTION2;

    private BarEnum barmember;

    private void switchBarmember() {
        switch (barmember) {
            case OPTION1: barmember = OPTION1; break;
            case OPTION2: barmember = OPTION2; break;

        }
    }
}

Upvotes: 1

Related Questions