0
0

More than 1 year has passed since last update.

【Java】 spullara/mustacheを使ってRuby風の文字列の式展開を行う

Posted at

概要

Javaで文字列中に変数の値を埋め込みたいという場合、+演算子でつなぐかString.formatを使うかと言ったところが、主な選択肢になるような気がします。ただ、どちらの方法も個人的にはあまりソースの可読性が良いとは感じず、できれば【Ruby】 式展開を使って文字列の中で変数を使おうの記事にあるような形で、変数を埋め込みたいところです。
ということで、今回はなんとかRubyのような感じでJavaでも書けないかということで、記事を書いてみます。

対応方針

  • こちらのstackoverflowの記事にあるように、Mushtacheというテンプレートエンジンを使えば、それっぽく書けるように感じました。ということで、Mushtacheを使って実装してみる方針とします。

前提など

  • Mushtacheについて、調べるといくつかライブラリが存在するようですが、今回はspullara/mustache.javaを使用してみます。2021年9月時点で、直近で更新もされているように見受けられるので。
  • spullara/mustacheのバージョンについては0.9.10を前提とします。

実装サンプル

spullara/mustacheのドキュメントによると、クラスのプロパティを埋め込む方式と、Mapオブジェクトに設定したkey・valueで埋め込む方式があります。実装サンプルでは2つの方法を試してみてます。
また、文字列を変数で使用することも想定し、StringWriterに出力しています。

StringInterpolation.java
public class StringInterpolation {

    @Builder
    static class Item {
        String id, name;
        Item(String id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    public static void main(String[] args) {
        try {
            // クラスの変数で式展開
            StringWriter sw = new StringWriter();
            MustacheFactory mf = new DefaultMustacheFactory();
            Mustache mustache = mf.compile(new StringReader("id:{{id}}、name:{{name}}"), "exampleClass");
            mustache.execute(
                    new PrintWriter(sw),
                    Item.builder().id("classId").name("className").build()
            ).flush();
            System.out.println(sw.toString());

            // Mapで式展開
            HashMap<String, String> scopes = new HashMap<String, String>();
            scopes.put("id", "mapId");
            scopes.put("name", "mapName");
            sw = new StringWriter();
            mf = new DefaultMustacheFactory();
            mustache = mf.compile(new StringReader("id:{{id}}、name:{{name}}"), "exampleMap");
            mustache.execute(new PrintWriter(sw), scopes).flush();
            System.out.println(sw.toString());
        } catch (IOException e) {
            System.out.println("IOException");
        }

    }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0