Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.format with lazy evaluation

Tags:

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.

like image 605
Juha Syrjälä Avatar asked Jun 03 '09 06:06

Juha Syrjälä


1 Answers

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.

like image 138
Andreas Petersson Avatar answered Oct 03 '22 11:10

Andreas Petersson