Java: enum toString ()

I created an enumeration, and I'm trying to allow my enumeration to support the String.format operation, which receives an unlimited number of parameters, returns a string. I managed to return the object, and after using this method I have to do toString() / casting. I assume there is a cleaner way to do this, or it might be better to use the toString() method. Basically, I wanted to support the toString() method, but, unfortunately, could not do this, so I created this method. As you can see, this is called text(..) , not toString() .

How can I do it 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); } }; } } 
+6
source share
2 answers

I see where you are going ... I think this is what you want (verified, and it works):

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

For the project point of view, I would not publish the text (i.e. had a getter) if you really do not need to - the fact that text used as a format string is the choice of implementation. I would just 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. Have not seen this before.

+9
source

You cannot override toString() if you need to pass more parameters ( toString() does not receive). Just define a new method in the listing, no need to redefine:

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

You should not call this method toString() , it will be confused because you are not returning a string representation of the current object, instead you are returning a formatted string of objects passed as parameters. Also, the text() method should be called getText() , which is the Java convention.

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

+4
source

Source: https://habr.com/ru/post/913564/


All Articles