toString() 생성기: 형식 템플리트

형식 템플리트는 생성된 메소드의 출력 문자열의 형식을 변경할 수 있게 하는 단순 메커니즘에서 사용됩니다: 시작, 종료, 구분 기호 등. JDT 코드 템플리트와 유사하지만 생성된 코드에 직접 영향을 미치지 않습니다(코드 스타일이 사용됩니다). 사용 가능한 템플리트 변수 목록은 다음과 같습니다.

${object.className}클래스 이름을 단순 문자열로 삽입합니다.
${object.getClassName}this.getClass.getName()에 대한 호출을 삽입합니다.
${object.superToString}super.toString()에 대한 호출을 삽입합니다.
${object.hashCode}this.hashCode()에 대한 호출을 삽입합니다.
${object.identityHashCode}System.identityHashCode(this)에 대한 호출을 삽입합니다.
${member.name}첫 번째 멤버 이름을 삽입합니다.
${member.name()}메소드의 경우 첫 번째 멤버 이름과 괄호를 삽입합니다.
${member.value}첫 번째 멤버 값을 삽입합니다.
${otherMembers}나머지 멤버를 삽입합니다. 각 멤버마다, 첫 번째와 마지막 ${member.*} 변수 간 템플리트 단편이 평가되어 결과에 추가됩니다. 마지막 ${member.*} 및 ${otherMembers} 간의 문자는 멤버간에 삽입되는 구분 기호를 정의합니다(${otherMembers}는 마지막 ${member.*} 변수 이후에 와야 합니다).

템플리트가 적절하게 작업하려면, ${otherMembers} 변수가 템플리트에서 정확히 한 번 사용되어야 하며 ${member.*} 변수가 다음에 올 수 없습니다. ${object.*} 변수는 템플리트 어디에나 위치할 수 있지만, 멤버 관련 단편에 위치하는 경우(즉, 첫 번째 ${member.*} 변수와 ${otherMembers} 사이), 적절한 솔루션이 아닌 모든 멤버에 대해 반복됩니다.

위의 설명은 복잡한 것 같지만, 템플리트 형식 자체는 매우 사용하기 쉽습니다. 몇 가지 작업 예제를 보면 이해하는 데 많은 도움이 됩니다.

템플리트 예제

  1. 기본 템플리트는 좋은 예제입니다.

    ${class.name} [${member.name()}=${member.value}, ${otherMembers}]

    이 템플리트의 출력 문자열은 다음과 같습니다.

    FooClass[aFloat=1.0, aString=hello, anInt=10, anObject=null, aCharMethod()=a]
  2. 여러 행 출력도 사용 가능합니다.

    ${object.getClassName} {
    	${member.name}: ${member.value}
    	${otherMembers}
    }

    Example result:

    FooClass {
    	aFloat: 1.0
    	aString: hello
    	anInt: 10
    	anObject: null
    	aCharMethod: a
    }
  3. 멤버를 중괄호로 묶은 경우, ${otherMembers} 변수로 동일하게 수행하는 것을 잊지 마십시오.

    {${member.name}=${member.value}},
    {${otherMembers}}

    Here's the effect:

    {aFloat=1.0},
    {aString=hello},
    {anInt=10},
    {anObject=null},
    {aCharMethod=a}
  4. ${object.*} 변수는 템플리트의 시작과 끝에서 사용될 수 있습니다.

    ${object.getClassName} (hashcode:${object.hashCode})
    	members: ${member.name} = ${member.value}; ${otherMembers}
    [super: ${object.superToString}]

    이 템플리트는 다음과 유사한 출력 결과를 가져옵니다.

    FooClass (hashCode:232198409832)
    	members: aFloat = 1.0; aString = hello; anInt = 10; anObject = null; aCharMethod = a
    [super: SuperFooClass[aField=null]]

관련 참조

toString() 생성 대화 상자
toString() 생성기: 코드 스타일
toString() 생성기: 컨텐츠 목록