Question

I have some variables in an enum that for some reason have to start with '@', for example:

public enum PR304MainDb {
    @MODE,
    @USERID,
    @ROLES,
    @MAX_DOC_COUNT
}

The way I use these variables is to put them in a HashMap...:

Map<String, Object> in = new HashMap<String, Object>();
in.put(PR304MainDb.@MODE.toString(), 5);

...and then use the HashMap as parameters when calling a store procedure (which code I can't change).

Also after the call I read the results and do some comparisons, like:

if (out.getKey().equals(PR304MainDb.@MAX_DOC_COUNT.toString())) {
//DO SOMETHING
}

I know that these names are invalid, but is there any alternative way to accomplish this?

Was it helpful?

Solution

Yes there is a way - don't use the enum constant name (don't use YOUR_CONSTANT.toString() as the name).

Enums, like other classes, can have fields and methods. Some possibilities:

public enum PR304MainDb_Possibility1 {
    MODE("@MODE"),
    USERID("@USERID"),
    ROLES("@ROLES"),
    MAX_DOC_COUNT("@MAX_DOC_COUNT");

    private PR304MainDb_Possibility1(String text) {
        this.text = text;
    }

    public final String text;
}

public enum PR304MainDb_Possibility2 {
    MODE,
    USERID,
    ROLES,
    MAX_DOC_COUNT;

    public String getText() {return "@" + name();}
}

OTHER TIPS

You can't use @ in the symbol name, but what you can do is over-ride the toString method:

public enum PR304MainDb {
    MODE,
    USERID,
    ROLES,
    MAX_DOC_COUNT;


    @override
    String toString() {
        return "@"+super.toString();
    }
}

You can also do this not using the toString() method at all by defining a new method for the purpose, but that would involve changing the code that is using the enum.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top