简体   繁体   中英

Importing an enum that is nested within another class from a different package(Java)

How to pass the value of an enum declared within another class to a method of that class?

In my other class which is in a different package from where the enum is defined, I have declared the enum as:

public static enum Status
{
  SUCCESS, FAILURE;
}

I've tried to import the Enum using import static as follows:

import static com.org.xx.yy.classname.Status

and

import com.org.xx.yy.classname.Status;

With both the cases in my test program, I am able to compile but I am getting a run time error:

Exception in thread "main" java.lang.NoClassDefFoundError: com.org.xx.yy.classname$Status

If you aren't getting a compile error for missing that class but you are getting the runtime NoClassDefFoundError then that means you must have linked against that class at compile time, without actually compiling it into your executable code, then you run your code without that class on the classpath so it can't find it.

Make sure that your build path is setup correctly to compile that class and try re-building your project OR, if that should be an external class, then add it to your classpath at runtime.

This compiles for me and prints out "SUCCESS"

Main.java

package com.xx.yy.Main;
import com.aa.bb.OtherClass.Status; // <-- Other class in other package

public class Main {
    public static void main(String[] args) {
        System.out.println(Status.SUCCESS.name());
    }
}

OtherClass.java

package com.aa.bb;

public class OtherClass {
    public static enum Status {
        SUCCESS, FAILURE;
    }
}

enum and nested enum - package local, final and static. No need to set static enum. import com.org.xx.yy.classname.Status should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM