使用类属性在 Java 中格式化字符串

Jas*_*mbs 5 java string-formatting

我有一个带有属性和 getter 方法的类:

public Class MyClass
{
  private String myValue = "foo";

  public String getMyValue();
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在格式化字符串中使用 foo 的值,如下所示:

String someString = "Your value is {myValue}."
String result = Formatter.format(someString, new MyClass());
// result is now "Your value is foo."
Run Code Online (Sandbox Code Playgroud)

也就是说,我想要一些像.format上面这样的函数,它采用指定某个对象属性的格式字符串以及具有这些属性的实例,并相应地格式化字符串。

用Java可以实现这个壮举吗?

Ste*_*oey 3

你可以使用JUEL来实现这一点。它是 Java 表达式语言的实现。代码相当紧凑,如下所示:

ExpressionFactory factory = new ExpressionFactoryImpl();

// create a context and add a Person object to the context, this variable will be used
// in the property replacement
// objects of type Person have two fields: firstName and lastName

SimpleContext context = new SimpleContext();
Person person = new Person("John", "Doe");
context.setVariable("person", factory.createValueExpression(person, Person.class));

// create the expression

String expr = "My name is ${person.firstName} ${person.lastName}";
ValueExpression e = factory.createValueExpression(context, expr, String.class);

// evaluate the expression
System.out.println(e.getValue(context));
Run Code Online (Sandbox Code Playgroud)

打印“我的名字是约翰·多伊”

请注意,也可以使用如下表达式:“${firstName}”而不是“${person.firstName}”,但是您必须为变量和属性解析