Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use Java Enums being DRY with only a single parameter different between instantiations?
    text
    copied!<p>I'm trying to figure out if there is a clean way of doing this. I want to design an ENUM to maintain a list of constant values for different components in my application. Each enum would have the same configuration and same parameters, but would differ at the very least by component name.</p> <p>In a normal Java class, I could build all the basic logic/code in a base abstract class, and have each component constants extend the abstract class and populate only its own pertinent information. However, Java enums do not allow extending existing classes.</p> <p>Is there something I can do to avoid having to either push all my constants in a single Enum (ugggg!) or recreate the same enum class each time for each differing component? Definitely not DRY in that case, but I do not know how to avoid the issue.</p> <p>For a quick use-case example off the top of my head. Say I want to keep a list of all my request mappings in an Enum for use elsewhere in my application. Fairly easy to design an enum that says:</p> <pre><code>public enum RequestMapping { INDEX("index"), GET_ALL_USERS( "getAllUsers"); private String requestMapping = "/users"; private String path; RatesURI( String path ){ this.path = path; } public String getRequestMapping(){ return requestMapping; } public String getPath(){ return path; } public String getFullRequestPath(){ return requestMapping + "/" + path; } } </code></pre> <p>It becomes easy to use RequestMapping.GET_ALL_USERS.getFullRequestPath().</p> <p>Now if I want to create this enum on a per-controller basis, I would have to recreate the entire Enum class and change the "requestMapping" value for each one. Granted, this enum has nearly no code in it, so duplicating it would not be difficult, but the concept still remains. The theoretical "clean" way of doing this would be to have an abstract AbstractRequestMapping type that contained all the methods, including an abstract getRequestMapping() method, and only have the extending Enums implement the controller-specific getReqeuestMapping(). Of course, since Enums cannot be extended, I can't think of a non DRY way of doing this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload