java – 如何使用bean中的属性格式化字符串

我想使用格式创建一个String,用bean中的属性替换格式的一些标记.是否有支持功能的库或者我是否必须创建自己的实现?

让我举一个例子来证明.说我有一个豆人;

public class Person {
  private String id;
  private String name;
  private String age;

  //getters and setters
}

我希望能够指定类似的格式字符串;

"{name} is {age} years old."
"Person id {id} is called {name}."

并使用bean中的值自动填充格式占位符,例如;

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属性.

解决方法

滚动我自己,现在测试.欢迎评论.
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);
  }

}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...