Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do a static import of a private subclass?

I have an enum which is private, not to be exposed outside of the class. Is there anyway I can do a static import of that type, so that I don't have to type the enum type each time? Or is there a better way to write this? Example:

package kip.test;

import static kip.test.Test.MyEnum.*; //compile error

public class Test
{
  private static enum MyEnum { DOG, CAT }

  public static void main (String [] args)
  {
    MyEnum dog = MyEnum.DOG; //this works but I don't want to type "MyEnum"
    MyEnum cat = CAT; //compile error, but this is what I want to do
  }
}
like image 612
Kip Avatar asked Jan 12 '10 03:01

Kip


2 Answers

Considering that you can access the field fully qualified, I would say that it is a bug in the compiler (or language spec) that you cannot statically import it.

I suggest that you make the enumeration package-protected.

like image 104
Thilo Avatar answered Sep 20 '22 20:09

Thilo


You can use the no-modifier access level, i.e.

enum MyEnum { DOG, CAT }

MyEnum will not be visible to classes from other packages neither from any subclass. It is the closest form of private, yet letting you avoid explicitly referencing MyEnum.

like image 40
Sug Avatar answered Sep 21 '22 20:09

Sug