Skip to content

Instantly share code, notes, and snippets.

@ledlogic
Created August 1, 2014 02:29
Show Gist options
  • Save ledlogic/d99e01c66399350a3bfb to your computer and use it in GitHub Desktop.
Save ledlogic/d99e01c66399350a3bfb to your computer and use it in GitHub Desktop.
Simple from string builder (reverse of a ToStringBuilder).
public class FromStringBuilder {
/**
* Parses a string formatted with toStringBuilder
*
* @param input - ex. "Path[id=1039916,displayName=School Home,description=<null>,...]"
* @return hashmap of name value pairs - ex. id=1039916,...
*/
public static Map<String, String> stringToMap(String input) {
LinkedHashMap<String, String> ret = new LinkedHashMap<String, String>();
String partsString = StringUtils.substringBetween(input, "[", "]");
String[] parts = partsString.split(",");
for (String part:parts) {
String[] nv = part.split("=");
if (!StringUtils.equals("<null>", nv[1])) {
ret.put(nv[0], nv[1]);
}
}
return ret;
}
public static <T> T stringToObject(String input, Class<T> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
Map<String, String> map = stringToMap(input);
T ret = clazz.newInstance();
BeanUtils.copyProperties(ret, map);
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment