How to use constants in enum parameter values from the same file in Java?

StackOverflow https://stackoverflow.com/questions/23392417

  •  12-07-2023
  •  | 
  •  

Question

I got a situation in my project, in which I have to modify/refactor an enum file and to use better coding standards. I am even not allowed to create a new constant file or such.

Below is a sample of my problem-

    public enum Enumtricks {

        // 1. private static final String DESC = "A String";

        ELEMENT("A String");    // want to use constant DESC

        // 2. private static final String DESC = "A String";


        private final String description;

        private Enumtricks(String description) {
            this.description = description;
        }

        public String value() {
            return this.description;
        }

    }

For both the cases I am getting errors, messages are- 1> Syntax error on token "String" 2> Cannot reference a field before it is defined

So, Is there a way to define constants & use them and to avoid String literals?

Était-ce utile?

La solution

Or add an interface outside of your enum but inside of the same compilation unit (= same file) as follows:

package test;

interface Constants {
    String DESC = "A String";
}

public enum Enumtricks {
    Enumtricks(Constants.DESC);
    private final String description;
    private Enumtricks(final String description) {
        this.description = description;
    }
    public String value() {
        return this.description;
    }
}

That way, you can group all your constants in front of your enum.

Autres conseils

Your constraints are very weird. If I understand correctly you would like to have several enums in one file. This in theory is possible like this - BUT I DO NOT RECOMMEND IT:

public class EnumCollection {

    public enum Enumtricks  {

        ELEMENT1("A String"),
        ELEMENT2("Another String"),
        ELEMENT3("Yet another String");

        private final String description;

        private Enumtricks(String description) {
            this.description = description;
        }

        public String value() {
            return this.description;
        }

    }

    public enum AnotherEnum {
        EN, UM, SA, RE, CO, OL;
    }
}

This is the closest I can get you to using Constants in the same file as your enums.

public enum Enumtricks {
    ELEMENT(EnumConstants.DESC);

    private final String description;

    private Enumtricks(String description) {
        this.description = description;
    }

    public String value() {
        return this.description;
    }

    private static class EnumConstants {
        private static final String DESC = "A String";
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top