How to call an enum from another class?

12,535

Solution 1

Enums are predefined objects, it will have a private constructor, You can not create a new instance with new. You just need to call Option.OPTION_1;

Response{
option = Option.OPTION_1; 
}

Solution 2

You just need to reference it as Options.OPTION_1 there's no new on enums.

Option option = Options.OPTION_1;

Solution 3

You cannot instantiate an enum object, the only instances that are there are defined by you in the enum class.

So the correct way is:

Response {
    option = Options.OPTION_1;
}

Solution 4

You cannot create a new instance of an enum. There is no need to because it can hold only fixed number of values. So option = new Option.OPTION_1("Option_1") will do.

Solution 5

Not aware of the grails part in this, but your usage of enum seems to be incorrect

If you have an enum as

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You can access individual value using Day.MONDAY, Day.SUNDAY, etc.

Please check the java doc.

Share:
12,535
chemilleX3
Author by

chemilleX3

Updated on July 17, 2022

Comments

  • chemilleX3
    chemilleX3 almost 2 years

    I am currently working on a grails project. I've created an enum located on a certain project folder, and wanted to access it from a class located on another project folder. My enum looks something like this:

    public enum Options {  
    
    
    OPTION_1("Option_1"),
    OPTION_2("Option_2"),
    OPTION_3("Option_3");
    
    final String option;
    
    Options(String option) {
        this.option = option;
    }  
    

    }

    Now, I am having a problem in calling that enum from a certain class in my application. For example:

    Response{
    option = new Option.OPTION_1("Option_1") //not sure on how to call an enum
    }
    

    But what I wanted to do here is to assign the enum to the property option in the Response {} section..

    How will I properly do that? Help please? Thanks.

  • Jayan
    Jayan over 11 years
    @ Rp- : your comment said not to use new. But the code had. I removed the 'new'. Hope that is fine.
  • RP-
    RP- over 11 years
    Yeah.. Copied the code from OP's question, Thanks for the edit
  • chemilleX3
    chemilleX3 over 11 years
    I think grails and java do same way in declaring enums, since grails is based in java..