1) Formatter에서 "%"기반 자리 표시 자 사용을 피할 수 없습니다. 그래서 Formatter/Formattable은 해결책이 아닙니다.
2) {} 자리 표시자를 매개 변수 값으로 바꾸는 방법이 필요한 경우 쉽게 구현할 수 있습니다.
public static String insertPlaceholders(String template, Object... args) {
if (args.length == 0) {
return template;
}
// best guess for capacity
final StringBuilder sb = new StringBuilder(template.length() + args.length * 8);
int index = 0;
int offset = 0;
while (index < args.length) {
final int p = template.indexOf("{}", offset);
if (p < 0) {
break;
}
sb.append(template, offset, p);
sb.append(args[index]);
offset = p + 2;
++index;
}
sb.append(template, offset, template.length());
return sb.toString();
}
단위 테스트 :
@Test
public void testInsertPlaceholders() {
assertSame("Test", StringUtils.insertPlaceholders("Test"));
assertEquals("Test", StringUtils.insertPlaceholders("Test", 1));
assertEquals("Test 2", StringUtils.insertPlaceholders("Test {}", 2));
assertEquals("Test 3 {}", StringUtils.insertPlaceholders("Test {} {}", 3));
assertEquals("Hello World!", StringUtils.insertPlaceholders("Hello {}!", "World"));
}
당신이 지금까지 작성한 것으로, 로깅/포맷을 처리하는 코드를 입력하십시오. – Korashen
정확히 무엇을 할 수 있습니까? 매개 변수 자리 표시자를 포함하는 문자열 만 변경하면됩니다. 아니면 내가 당신의 질문을 오해하고 있습니까? – Bombe
Log4j를 살펴볼 가치가 있습니다. – JBA