May 19, 2014

FromStringBuilder

Created a quick and dirty FromStringBuilder.java class utility.
public class FromStringBuilder {

 /**
  * Parses a string formatted with toStringBuilder
  * 
  * @param input - ex. "Path[id=1039916,displayName=School Home,description=,...]"
  * @return hashmap of name value pairs - ex. id=1039916,... 
  */
 public static Map stringToMap(String input) {
  LinkedHashMap ret = new LinkedHashMap();
  String partsString = StringUtils.substringBetween(input, "[", "]");
  String[] parts = partsString.split(",");
  for (String part:parts) {
   String[] nv = part.split("=");
   if (!StringUtils.equals("", nv[1])) {
    ret.put(nv[0], nv[1]);
   }
  }
  return ret;
 }
 
 public static  T stringToObject(String input, Class clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
  Map map = stringToMap(input);
  T ret = clazz.newInstance();
  BeanUtils.copyProperties(ret, map);
  return ret;
 }
}

Also mentioned on stackoverflow

No comments:

Post a Comment