tags:

views:

95

answers:

3

I'm looking for a smart Java String formatter similar to the standard Formatter:

    StringBuffer buffer = new StringBuffer();
    Formatter formatter = new Formatter(buffer);
    formatter.format("hello %1$s, %2$s and %3$s", "me", "myself", "I");

The problem is that if you make a mistake in the format (e.g. you forget the $s) an exception will be thrown. Not really what I want when formatting an error message (since it's not in the regular path of the application and may not be tested).

I could of course define my own class, let's say accept a string like "hello $1, $2 and $3, do the replacement with ($1 -> %1$s) and invoke the toString() for all parameters but I'm sure a better solution has been already developed.

Somewhere, in some jar...

Thanks for any useful pointer.

EDIT

I'm looking for something that like the following:

String out = MySpecialFormatter.format("hello $1, $2 and $3", "me", "myself", "I");

if you have an error in your format (well, typos exist), it tries its best to fill in the bind variables, or return the original format string.

+1  A: 

The problem is that if you make a mistake in the format (e.g. you forget the $s) an exception will be thrown. Not really what I want when formatting an error message (since it's not in the regular path of the application and may not be tested).

So you're basically asking "If I haven't tested my code and it's wrong, what can I use to hide that instead of having to deal with it?"

The solution is to properly test all your code. When you write it, preferably.

If you insist on covering up your bad code and pretending it's not there, you could do the following:

public class LazyProgrammersFormatter {
    private Formatter _f;

    public LazyProgrammersFormatter(Formatter f) {
        _f = f;
    }

    public bool format(/*can't be bothered looking up the varargs signature, you know what it is*/) {
        try {
            _f.format(/*etc.*/);
            return true;
        } catch (FormatException e) {
            return false;
        }
    }
}
Anon.
A: 

Is String.format not suitable for what you are looking for? Java doc for string format.

Teja Kantamneni
thanks for the pointer but unfortunately it also works with the `%1$s` format and also throws an exception, so not exactly what I would like.
Vladimir
A: 

Sometimes the answer is right there...

import static java.text.MessageFormat.format;

String out = format("hello {0}, {1} and {2}", "me", "myself", "2", "3");

And yes, Anon, apparently Sun thought that all the programmers where that lazy.

Vladimir