Java – how to format strings using properties in beans

I want to create a string using the format and replace some tags in the format with properties in the bean Is there a library that supports this feature, or do I have to create my own implementation?

Let me give an example to prove it Say I have a bean man;

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

  //getters and setters
}

I want to be able to specify a similar format string;

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

And automatically fill the format placeholder with the values in the bean, for example;

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

I've seen @ R_ 301_ 660 @, but it seems that this only allows me to pass numeric indexes, not bean properties

Solution

Roll myself, test now Comments are 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);
  }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>