4.3.18 표현 템플릿 by ks

표현 템플릿은 하나 그이상의 평가 블록과 문자열을 합친 것이다. 각 평가 블록은 정의할 수 있는 prefix와 suffix 문자로 나눠진다. 공통의 선택은 #{}을 딜리미터로 쓰는 것이다.

String randomPhrase = parser.parseExpression(
        "random number is #{T(java.lang.Math).random()}",
        new TemplateParserContext()).getValue(String.class);

// evaluates to "random number is 0.7038186818312008"

문자열은 문자열 텍스트 #{} 딜리미터 안에 표현식을 평가하는 결과와 'random number is'를 집중해서 평가한다 (이 경우에 random() 메소드를 부른 결과이다.). parseExpression() 메소드에 두번째 인자는 ParserContext 타입이다. ParserContext 인터페이스는 표현식 템플릿 기능을 지원하기 위해 표현식이 구문 분석되는 방식에 영향을주기 위해 사용된다. 아래는 TemplateParserContext의 정의이다.

public class TemplateParserContext implements ParserContext {

    public String getExpressionPrefix() {
        return "#{";
    }

    public String getExpressionSuffix() {
        return "}";
    }

    public boolean isTemplate() {
        return true;
    }
}

Last updated