sl4fj와 유사한 일반적인 문자열 대체 기능이 있습니까?
문자열 메시지를 작성하려면 sl4fj를 사용하여 치환을 사용하는 좋은 방법이 있습니다.예를 들어 다음과 같은 경우가 있습니다.
logger.info("Action {} occured on object {}.", objectA.getAction(), objectB);
교환이 여러 개 필요한 경우 다음과 같습니다.
logger.info("Action {} occured on object {} with outcome {}.",
new Object[]{objectA.getAction(), objectB, outcome});
질문입니다. (slf4j 로그 메시지뿐만 아니라) 문자열을 작성하는 일반적인 방법이 있습니까?예를 들어 다음과 같습니다.
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 라이브러리에 있는 경우 "some Method"는 무엇입니까?
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});
숫자 위치를 사용할 수도 있습니다. 예를 들어 다음과 같이 파라미터를 전환할 수 있습니다.
String str = String.format("Action %2$s occured on object %1$s.",
objectA.getAction(), objectB);
String을 사용할 수 있습니다.형식 또는 메시지 형식입니다.포맷
예.,
MessageFormat.format("A sample value {1} with a sample string {0}",
new Object[] {"first", 1});
또는 간단히 말하면
MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1);
String 내의 변수 묶음을 값으로 대체할 수 있는 솔루션을 찾고 있는 경우 Str Substitutor를 사용할 수 있습니다.
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
일반적으로 받아들여지는 패턴을 따릅니다.이 패턴에서는 변수가 있는 맵을 미해결 문자열과 함께 값으로 전달하고 해결된 문자열을 반환합니다.
org.slf4j.helpers를 사용하는 것이 좋습니다.MessageFormatter.이를 통해 slf4j와 동일한 포맷 스타일을 사용하는 유틸리티 메서드를 만들 수 있습니다.
// utillity method to format like slf4j
public static String format(String msg, Object... objs) {
return MessageFormatter.arrayFormat(msg, objs).getMessage();
}
// example usage
public static void main(String[] args) {
String msg = format("This msg is {} like slf{}j would do. {}", "formatted", 4,
new Exception("Not substituted into the message"));
// prints "This msg is formatted like slf4j would do. {}"
System.out.println(msg);
}
메모: 어레이의 마지막 객체가 예외일 경우 slf4j 로거와 같이 메시지에서 대체되지 않습니다.예외에 액세스하려면MessageFormatter.arrayFormat(msg, objs).getThrowable().
원래 Joern Huxhorn이 Lilith용으로 작성한 Log4j2 Parameterized Message를 랩으로 선택합니다.
public static String format(final String messagePattern, Object... arguments) {
return ParameterizedMessage.format(messagePattern, arguments);
}
슬로우 가능의 불필요한 처리를 포함하는 SLF4J MessageFormatter와는 달리 메시지 포맷에 초점을 맞추고 있습니다.
자바독 참조:
교체 가능한 각 토큰과 매개 변수를 나타내는 '{}'을(를) 포함하는 형식 문자열로 구성된 메시지를 처리합니다.
언급URL : https://stackoverflow.com/questions/5057960/is-there-a-general-string-substitution-function-similar-to-sl4fj
'programing' 카테고리의 다른 글
| 이상한 MySQL 팝업 "Mysql 설치 프로그램이 커뮤니티 모드를 실행하고 있습니다." (0) | 2022.10.05 |
|---|---|
| adslash()를 통한 SQL 주입의 예? (0) | 2022.10.05 |
| 마리아답은 시동이 걸리지 않는다.제어 프로세스가 종료되었습니다. (0) | 2022.10.05 |
| PHP에서 현재 함수의 이름을 검색하는 중 (0) | 2022.10.05 |
| Java에서 a.getClass()와 A.class의 차이점은 무엇입니까? (0) | 2022.10.05 |