Java 14或15中的字符串插值

huangapple go评论137阅读模式
英文:

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}");

编辑:JEP 430涵盖了这个问题以及更多内容,已被提议用于目标JDK 21。

英文:

Since I am using Java 14 and 15 preview features. Trying to find the string interpolation in java.

The closest answer I found is

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

Since the answer which I got from lots fo references are old answers asked 4,5 years ago. Is there any update on the string interpolation in java 11,12,13,14,15 equivalent to C#

string name = "Horace";
int age = 34;
Console.WriteLine($"Your name is {name} and your age {age}");

EDIT: JEP 430, which covers this and much more, has been proposed to target JDK 21.

答案1

得分: 44

有一点 稍微 更接近;一个名为 formattedString::format 的实例版本:

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

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

英文:

There is something slightly closer; an instance version of String::format, called formatted:

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

It is similar to String::format, but is more friendly to use in chained expressions.

答案2

得分: 11

据我所知,标准的Java库中关于这种类型的字符串格式化并没有更新。

换句话说:你仍然只能使用String.format()及其基于索引的替换机制,或者你必须选择一些第三方库/框架,比如Velocity、FreeMarker,可以在这里初步了解。

英文:

To my knowledge, there are no updates in the standard java libraries regarding such kind of string formatting.

In other words: you are still "stuck" with either using String.format() and its index based substitution mechanism, or you have to pick some 3rd party library/framework, such as Velocity, FreeMarker, ... see here for an initial overview.

答案3

得分: 2

目前没有内置支持这个功能,但是可以使用Apache Commons TextStringSubstitutor

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."

该类支持为变量提供默认值。

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"
英文:

There is no built-in support for that currently, but Apache Commons Text's StringSubstitutor can be used.

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

This class supports providing default values for variables.

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

To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.

Map&lt;String, String&gt; values = new HashMap&lt;&gt;();
values.put(&quot;b&quot;, &quot;c&quot;);
values.put(&quot;ac&quot;, &quot;Test&quot;);
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace(&quot;${a${b}}&quot;);
// &quot;Test&quot;

答案4

得分: 0

你还可以像这样使用 MessageFormat(适用于 Java 5.0 或更高版本)

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

非常好。

英文:

You can also use MessageFormat like this (Java 5.0 or later)

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

Very nice

答案5

得分: -1

你可以使用Java的字符串模板功能。
它在JEP 430中有描述,并且在JDK 21中作为预览功能出现。以下是一个示例用法:

string name = "Horace";
int age = 34;
System.out.println(STR."Your name is {name} and your age {age}");
英文:

You can use Java's String Templates feature.
It is described in JEP 430, and it appears in JDK 21 as a preview feature. Here is an example use:

string name = &quot;Horace&quot;;
int age = 34;
System.out.println(STR.&quot;Your name is {name} and your age {age}&quot;);

答案6

得分: -2

看起来这些 Java 版本中没有可用的漂亮的 C# 风格插值我们为什么需要这个功能 - 是为了在代码中有漂亮且可读的行将文本转储到日志文件中

以下是可工作的示例代码其中有一行注释掉的 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;
    }

}
英文:

Looks like nice C#-style interpolation is not available in these Java versions. Why we need this - to have nice and readable lines of code dumping text to Log files.

Below is sample code that works (there is commented org.apache.commons.lang3.StringUtils which at some point of writing was required but later it was not) - it was dropping ClassNotFound or other NotFoundException - I have not investigated it.

The StringSubstitutor might be later packed in something nicer that will make it easier to use for Log message dumping

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(&quot;Starting program&quot;);
		
		var result =  adding(1.35,2.99);

		Map&lt;String, String&gt; values = new HashMap&lt;&gt;();
		values.put(&quot;logMessageString&quot;, Double.toString(result) );

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

		System.out.println(logMessage);
		System.out.println(&quot;Ending program&quot;);
		 
	}
	// 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;
	}

}

huangapple
  • 本文由 发表于 2020年8月24日 18:27:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63559237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定