Juha Syrjälä Juha Syrjälä - 2 months ago 20
Java Question

String.format with lazy evaluation

I need something similar to String.format(...) method, but with lazy evaluation.

This lazyFormat method should return some object whose toString() method would then evaluate the format pattern.

I suspect that somebody has already done this. Is this available in any libararies?

I want to replace this (logger is log4j instance):

if(logger.isDebugEnabled() ) {
logger.debug(String.format("some texts %s with patterns %s", object1, object2));
}


with this:

logger.debug(lazyFormat("some texts %s with patterns %s", object1, object2));


I need lazyFormat to format string only if debug logging is enabled.

Answer

if you are looking for a "simple" solution:

 public class LazyFormat {

    public static void main(String[] args) {
        Object o = lazyFormat("some texts %s with patterns %s", "looong string", "another loooong string");
        System.out.println(o);
    }

    private static Object lazyFormat(final String s, final Object... o) {
        return new Object() {
            @Override
            public String toString() {
                return String.format(s,o);
            }
        };
    }
}

outputs:

some texts looong string with patterns another loooong string

you can of course add any isDebugEnabled() statement inside lazyFormat if you will.

Comments