Java 14 或 15 中的字符串插值

String interpolation in Java 14 or 15

因为我使用的是 Java 14 和 15 预览功能。试图在 java.

中找到字符串插值

我找到的最接近的答案是

String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4)

因为我从很多参考资料中得到的答案是 4.5 年前的旧答案。 java 11,12,13,14,15 等同于C#

中的字符串插值是否有任何更新
string name = "Horace";
int age = 34;
Console.WriteLine($"Your name is {name} and your age {age}");

据我所知,标准 java 库中没有关于此类字符串格式的更新。

换句话说:您仍然“坚持”使用 String.format() 及其基于索引的替换机制,或者您必须选择一些第 3 方 library/framework,例如 Velocity、FreeMarker, ...请参阅 here 了解初步概述。

有东西稍微近一些; String::format 的实例版本,称为 formatted:

String message = "Hi, %s".formatted(name);

它类似于String::format,但在链式表达式中使用更友好。

目前没有内置支持,但可以使用 Apache Commons StringSubstitutor

import org.apache.commons.text.StringSubstitutor;
import java.util.HashMap;
import java.util.Map;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."

此 class 支持为变量提供默认值。

String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."

要使用递归变量替换,调用setEnableSubstitutionInVariables(true);

Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"

看起来不错的 C# 插值在这些 java 版本中根本不起作用。 为什么我们需要这个 - 有漂亮且可读的代码行将文本转储到日志文件。 下面是有效的示例代码(有注释 org.apache.commons.lang3.StringUtils ,在某些时候需要编写但后来不需要) - 它正在丢弃 ClassNotFound 或其他 NotFoundException - 我没有调查过它.

StringSubstitutor 稍后可能会打包成更好的东西,这将使它更容易用于日志消息转储

package main;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.text.*;
//import org.apache.commons.lang3.StringUtils;

public class Main {

    public static void main(String[] args) {
        System.out.println("Starting program");
        
        var result =  adding(1.35,2.99);

        Map<String, String> values = new HashMap<>();
        values.put("logMessageString", Double.toString(result) );

        StringSubstitutor sub = new StringSubstitutor(values);
        sub.setEnableSubstitutionInVariables(true);
        String logMessage = sub.replace("LOG result of adding: ${logMessageString}");

        System.out.println(logMessage);
        System.out.println("Ending program");
         
    }
    // it can do many other things but here it is just for prcoessing two variables 
    private static double adding(double a, double b) {
        return a+b;
    }

}

您也可以像这样使用 MessageFormat(Java 5.0 或更高版本)

MessageFormat.format("Hello {0}, how are you. Goodbye {0}",userName);

很好