如何使用bean中的属性格式化字符串 [英] How do I format a string with properties from a bean
问题描述
我想使用格式创建一个String,用bean中的属性替换格式的一些标记。有没有一个支持这个的库,或者我将不得不创建自己的实现?
I want to create a String using a format, replacing some tokens in the format with properties from a bean. Is there a library that supports this or am I going to have to create my own implementation?
让我用一个例子来演示。假设我有一个bean Person
;
Let me demonstate with an example. Say I have a bean Person
;
public class Person {
private String id;
private String name;
private String age;
//getters and setters
}
我想要能够指定类似的格式字符串;
I want to be able to specify format strings something like;
"{name} is {age} years old."
"Person id {id} is called {name}."
并使用bean中的值自动填充格式占位符,例如;
and automatically populate the format placeholders with values from the bean, something like;
String format = "{name} is {age} old."
Person p = new Person(1, "Fred", "32 years");
String formatted = doFormat(format, person); //returns "Fred is 32 years old."
我看过 MessageFormat
但这似乎只允许我传递数字索引,而不是bean属性。
I've had a look at MessageFormat
but this only seems to allow me to pass numeric indexes, not bean properties.
推荐答案
滚动我自己,现在进行测试。欢迎评论。
Rolled my own, testing now. Comments welcome.
import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BeanFormatter<E> {
private Matcher matcher;
private static final Pattern pattern = Pattern.compile("\\{(.+?)\\}");
public BeanFormatter(String formatString) {
this.matcher = pattern.matcher(formatString);
}
public String format(E bean) throws Exception {
StringBuffer buffer = new StringBuffer();
try {
matcher.reset();
while (matcher.find()) {
String token = matcher.group(1);
String value = getProperty(bean, token);
matcher.appendReplacement(buffer, value);
}
matcher.appendTail(buffer);
} catch (Exception ex) {
throw new Exception("Error formatting bean " + bean.getClass() + " with format " + matcher.pattern().toString(), ex);
}
return buffer.toString();
}
private String getProperty(E bean, String token) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Field field = bean.getClass().getDeclaredField(token);
field.setAccessible(true);
return String.valueOf(field.get(bean));
}
public static void main(String[] args) throws Exception {
String format = "{name} is {age} old.";
Person p = new Person("Fred", "32 years", 1);
BeanFormatter<Person> bf = new BeanFormatter<Person>(format);
String s = bf.format(p);
System.out.println(s);
}
}
这篇关于如何使用bean中的属性格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!