本文介绍了是否有类似于sl4fj的通用字符串替换功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用sl4fj,如果我想构造一个字符串消息,有一个很好的方法,它使用替换。例如,它可能类似于:

With sl4fj if I want to construct a string message there is a nice approach which makes use of substitutions. For instance, it might be something like:

logger.info("Action {} occured on object {}.", objectA.getAction(), objectB);

如果需要更多替换,则类似于:

If there are more than a few substitutions required then it is something like:

logger.info("Action {} occured on object {} with outcome {}.",
    new Object[]{objectA.getAction(), objectB, outcome});

我的问题是:我是否有通用的方法来创建字符串(而不仅仅是slf4j)日志消息)?类似于:

My question is: Is there a generic way for me to create a string (and not just a slf4j log message)? Something like:

String str = someMethod("Action {} occured on object {}.", objectA.getAction(), objectB);

String str = someMethod("Action {} occured on object {} with outcome {}.",
    new Object[]{objectA.getAction(), objectB, outcome});

如果它在标准Java库中,那么someMethod会是什么?

If it is in the standard Java library, what would that "someMethod" be?

推荐答案

String str = String.format("Action %s occured on object %s.",
   objectA.getAction(), objectB);

String str = String.format("Action %s occured on object %s with outcome %s.",
   new Object[]{objectA.getAction(), objectB, outcome});

您还可以使用数字位置,例如切换参数:

You can also use numeric positions, for example to switch the parameters around:

String str = String.format("Action %2$s occured on object %1$s.",
   objectA.getAction(), objectB);

这篇关于是否有类似于sl4fj的通用字符串替换功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 12:13