当前位置: 动力学知识库 > 问答 > 编程问答 >

string - Java: enum toString()

问题描述:

I have created an enum and I'm trying to allow my enum to support a String.format operation that gets unlimited number of parameters are return a string.

I only managed to return an object and after using this method I have to do a toString()/casting. I am guessing there's a more "clean" way to do it, or maybe to override better the toString() method. Basically, I wanted to support the toString() method but sadly didn't manage to do that so I created this method. As you can see it's named text(..) and not toString().

How can I do this better? The ideal solution I wanted was something like toString(..) which returns a String.

public enum MY_ENUM {

VALUE_A("aaa %s"), VALUE_B("bbb %s");

private String text;

MY_ENUM(String text) {

this.text = text;

}

public String text() {

return this.text;

}

public Object text(final Object... o) {

return new Object() {

@Override

public String toString() {

return String.format(text(), o);

}

};

}

}

网友答案:

I see where you're going... I think this is what you want (tested, and it works):

public String toString(Object... o) {
    return String.format(text, o);
}

For a design point of view, I would not publish the text (ie have the getter) unless you really need to - the fact that text is used as a format string is an implementation choice. I would simply do this:

public static enum MY_ENUM {

    VALUE_A("aaa %s bbb %s"),
    VALUE_B("bbb %s");

    private final String text;

    MY_ENUM(String text) {
        this.text = text;
    }

    public String toString(Object... o) {
        return String.format(text, o);
    }
}

As an aside, I really like the idea of the class. Haven't seen it before.

网友答案:

You can't override toString() if you need to pass more parameters (toString() doesn't receive any). Simply define a new method in the enum, no need to override:

public String getAsFormattedText(Object... o) {
    return String.format(text, o);
}

You shouldn't name this method toString(), it'd be confusing because you're not returning the string representation of the current object, instead you're returning a formatted string of the objects passed as parameters. Also, the text() method should be called getText(), that's the Java convention.

Better use a name that clearly indicates that the returned string is not any string - it's a formatted string that expects the text to be formatted as a parameter - getAsFormattedText() clearly expresses this.

分享给朋友:
您可能感兴趣的文章:
随机阅读: