Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using constant strings as Enum constructor parameters

Tags:

java

enums

I'm trying to write a REST endpoint to return data depending on the staff type. And the staff are categorised according to their role within the organisation, like so.

public enum StaffType {
    ADMIN("Admin"),
    CASUAL("Casual"),
    CORE("Core"),
    MANAGEMENT("Management");

    private String type;

    StaffType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }
}

Now in my REST endpoint, I cannot refer to these enums explicitly. The best I can do is refer to the String text associated with each, E.g. "Admin" or "Casual".

@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
             @RequestParam(value = "", required = false, defaultValue = "Admin")
                      StaffType staffType) {

But I do not like repeating this same string in two places when they are directly linked, and should always be the same.

So I thought of creating a constants, and having both refer to the constants in that class

public class Constants {
    public static String ADMIN = "Admin";
    public static String CASUAL = "Casual";
    ...
}

public enum StaffType {
    ADMIN(Constants.ADMIN),
    CASUAL(Constants.CASUAL),
    ...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
             @RequestParam(value = "", required = false, defaultValue = Constants.ADMIN)
                      StaffType staffType) {

My question is, does there a better, more widely accepted way to solve this problem? Or is this an appropriate solution?

like image 281
pdc Avatar asked Oct 19 '25 21:10

pdc


1 Answers

Looks appropriate to me. However I would put the string constants inside the enum class though, that's better place to put them as they belong together with the enum constants. To get around the "no forward references" constraint you can put them in a static inner class inside the enum:

public enum StaffType {
    ADMIN(Strings.ADMIN), 
    CASUAL(Strings.CASUAL);

    public static class Strings {
        public static String ADMIN = "Admin";
        public static String CASUAL = "Casual";
    }

    // ...
}
@RequestMapping(value = "/staff", method = RequestMethod.GET)
public ResponseEntity getStaff(
        @RequestParam(value = "", required = false, defaultValue = StaffType.Strings.ADMIN)
                      StaffType staffType) {
like image 139
Erwin Bolwidt Avatar answered Oct 21 '25 13:10

Erwin Bolwidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!