Notice
Recent Posts
Recent Comments
Link
GitHub Contribution 그래프
Loading data ...
«   2026/02   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Youn's IT Memo

JEP 430. String 템플릿 (Preview) 본문

Language/Java

JEP 430. String 템플릿 (Preview)

bellman66 2023. 9. 2. 18:40

Summary

Java 21이 LTS가 되면서 향후 어떤 기능이 들어가는지 지속적으로 살펴보던 중 

가장 실무에 사용하기에 적합한 부분이 있는거 같아서 글을 남겨봅니다.

 

동기 부여 

모든 Java 개발자가 공통적으로 느끼는 부분으로 String 쓰는 방식이 참으로 불편하다는 느낌이 듭니다.

아래의 예시처럼 작성된 경우가 대다수 였던거 같습니다.

+를 통한 문자열 연결
String line = "hello " + number + "번 유저님";

StringBuilder나 Buffer를 이용한 문자열 연결
StringBuilder line = new StringBuilder().append("hello ")
		.append(number)
		.append("번 유저님");
        
StringFormat 
String line = String.format("hello $S번 유저님", number);

 

이런 문자열 방식에 익숙해서 괜찮지만 OpenJdk에서는 이렇게 설명되어 있습니다.

+ 연산자 : 너무 길어서 가독성이 안좋음

StringBuilder : 너무 장황해서 길어짐 -> 가독성 떨어짐

Format : 유형 불일치를 유발시킴 

 

다른 언어는 어떤 방식일까요?

다른 프로그래밍 언어의 경우 문자열을 체이닝하는 방식보다는 보간 방식을 제공합니다.

런타임시 해당 표현식 안에 있는 변수값을 문자화하여 대체하도록 됩니다. 

C#             $"{x} plus {y} equals {x + y}"
Visual Basic   $"{x} plus {y} equals {x + y}"
Python         f"{x} plus {y} equals {x + y}"
Scala          s"$x plus $y equals ${x + y}"
Groovy         "$x plus $y equals ${x + y}"
Kotlin         "$x plus $y equals ${x + y}"
JavaScript     `${x} plus ${y} equals ${x + y}`
Ruby           "#{x} plus #{y} equals #{x + y}"
Swift          "\(x) plus \(y) equals \(x + y)"

위와 같은 형태로 대부분의 언어들은 문자열을 지원하게 됩니다.

편리하고 직관적인 형태로 특히 사용하기에 편리해보입니다.

하지만 보간법도 Injection 공격으로 이어질 가능성이 있어 위험합니다. ( 특히 SQL Query문 생성시 )

 

STR 템플릿 프로세서

STR은 차후 제공될 템플릿 프로세서중 하나입니다. 문자열 보간을 지원하게 됩니다.

// Embedded expressions can be strings
String firstName = "Bill";
String lastName  = "Duck";
String fullName  = STR."\{firstName} \{lastName}";
| "Bill Duck"
String sortName  = STR."\{lastName}, \{firstName}";
| "Duck, Bill"

String filePath = "tmp.dat";
File   file     = new File(filePath);
String old = "The file " + filePath + " " + (file.exists() ? "does" : "does not") + " exist";
String msg = STR."The file \{filePath} \{file.exists() ? "does" : "does not"} exist";
| "The file tmp.dat does exist" or "The file tmp.dat does not exist"

// Embedded expressions can be postfix increment expressions
int index = 0;
String data = STR."\{index++}, \{index++}, \{index++}, \{index++}";
| "0, 1, 2, 3"

// Embedded expression is a (nested) template expression
String[] fruit = { "apples", "oranges", "peaches" };
String s = STR."\{fruit[0]}, \{STR."\{fruit[1]}, \{fruit[2]}"}";
| "apples, oranges, peaches"

String tmp = STR."\{fruit[1]}, \{fruit[2]}";
String s = STR."\{fruit[0]}, \{tmp}";

 

MultiLine Template

String title = "My Web Page";
String text  = "Hello, world";
String html = STR."""
        <html>
          <head>
            <title>\{title}</title>
          </head>
          <body>
            <p>\{text}</p>
          </body>
        </html>
        """;
| """
| <html>
|   <head>
|     <title>My Web Page</title>
|   </head>
|   <body>
|     <p>Hello, world</p>
|   </body>
| </html>

 

FMT 템플릿 프로세서

STR 템플릿 프로세서와 비슷하지만 표현식 왼쪽에 형식을 넣어서 표현할수 있도록 합니다.

Ex. %1.5f \{ VALUE }

record Rectangle(String name, double width, double height) {
    double area() {
        return width * height;
    }
}
Rectangle[] zone = new Rectangle[] {
    new Rectangle("Alfa", 17.8, 31.4),
    new Rectangle("Bravo", 9.6, 12.4),
    new Rectangle("Charlie", 7.1, 11.23),
};
String table = FMT."""
    Description     Width    Height     Area
    %-12s\{zone[0].name}  %7.2f\{zone[0].width}  %7.2f\{zone[0].height}     %7.2f\{zone[0].area()}
    %-12s\{zone[1].name}  %7.2f\{zone[1].width}  %7.2f\{zone[1].height}     %7.2f\{zone[1].area()}
    %-12s\{zone[2].name}  %7.2f\{zone[2].width}  %7.2f\{zone[2].height}     %7.2f\{zone[2].area()}
    \{" ".repeat(28)} Total %7.2f\{zone[0].area() + zone[1].area() + zone[2].area()}
    """;
| """
| Description     Width    Height     Area
| Alfa            17.80    31.40      558.92
| Bravo            9.60    12.40      119.04
| Charlie          7.10    11.23       79.73
|                              Total  757.69
| """

'Language > Java' 카테고리의 다른 글

Class 동기화 기법 ( mutex exclusion )  (0) 2023.10.01
Java 실험 | Comparator & Auto Boxing  (0) 2023.06.22