0

How do I access inner enum classes in another class? For example:

public class Foo {
    enum Bar {
        ONE, TWO, FOUR, EIGHT, SIXTEEN
    }

    // ...methods here
}

The class I am trying to access Foo.Bar in:

public class FooTest {
    private Foo f;

    @Before
    public void setUp() throws Exception {
        f = new Foo();
    }

    public void testCase1() {
        assertEquals(Bar.ONE, f.climbUp());
    }
}

I've tried Foo.Bar.ONE, Bar.ONE as well as making a new variable using Foo.class.getDeclaredField("Bar") but none of these seem to be working. getDeclaredClasses() seems to get me $Bar but I can't access anything from there.

Update: I'm not allowed to modify the class Foo

Raedwald
  • 46,613
  • 43
  • 151
  • 237
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • Make Bar public: `public static enum Bar` – Brett Okken Jun 30 '14 at 19:45
  • 1
    What do you mean with "not working" (compile error? runtime error? test fails?) and what does this have to do with reflection? – Jesper Jun 30 '14 at 19:45
  • 1
    If you need the enum to not be available from the outside world, but want it accessible for a test - the default level is `package-private`, so you could make the test in the same package. – nerdwaller Jun 30 '14 at 19:46
  • See also http://stackoverflow.com/questions/440786/junit-java-testing-non-public-methods – Raedwald Jun 30 '14 at 22:52

2 Answers2

1

If the goal is to test it, but keep the enum in the default accessibility (package-private), which is implied by your inability to edit Foo and the title of the other class, then a common approach is to make the test in the same package. Meaning it can access the items with default visibility (see here).

The test:

package com.scratch;

public class FooTest {
    public static void main(String[] args) {
        System.out.println(String.valueOf(Foo.Bar.ONE));
    }
}

The other source:

package com.scratch;

public class Foo {
    enum Bar {
        ONE, TWO;
    }
}
nerdwaller
  • 1,813
  • 1
  • 18
  • 19
0

You don't need to use reflection here. Just make the enum "static":

public class Foo {
    static enum Bar {
        ONE, TWO, FOUR, EIGHT, SIXTEEN
    }

    // ...methods here
}

Then you can access it thru Foo.Bar.ONE

evanwong
  • 5,054
  • 3
  • 31
  • 44
  • 1
    Forgot to mention that I cannot modify `Foo`. – rink.attendant.6 Jun 30 '14 at 19:47
  • 3
    **Enums are implicitly static** (see the [language spec](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#Enums)), it doesn't change if it can be accessed in this case or not. The issue here is the [Access Modifier](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) – nerdwaller Jun 30 '14 at 19:55