Wednesday, February 27, 2013

Enums in an Eclipse Scrapbook page

I was trying to do some quick testing of enums in an Eclipse Scrapbook (a jpage file). I am using JDK 1.7.0_02, Win XP 64-bit, Eclipse Juno.

class A {
    enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
}
A a = new A();

When I execute the above snippet I get this error:

The member enum Month can only be defined inside a top-level class or interface

I tried moving the enum out of the class definition with the following code.

enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
Month.valueOf("JAN");

And I still get the error, plus being unable to resolve Month:

The member enum Month can only be defined inside a top-level class or interface
Month cannot be resolved

Perhaps Eclipse just puts the code into a main method and runs it, in which case this error is understandable (you cannot define a local enum, even though you can define a local type). I believe the only way to do this is to move the enum itself out of the jpage into a new class. So I make the class like so:

package test;
public class Test {
   public enum Month {
      JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC;
   };
}

Then in the jpage, import the test package.

  1. Right click and select "Set Imports".
  2. Click "Add Packages" and enter/select the test package.

Finally, the jpage will only need the below code.

Test.Month.valueOf("JAN");

Which is all very unfortunate, because this completely defeats the purpose of using an Eclipse Scrapbook file. If I have to create a new class for the enum, I might as well forget the jpage, add a main method to Test.java and put the rest of testing code there!

I asked this question in a few other places because it was driving me mad.