codecentric

StringUtils.camelize(String);

Today I noticed that the Apache Commons libs are lacking a method to camelize Strings.

Because I needed to convert such an XML name MY_TINY_PROPERTY into a Java property name myTinyProperty, I ended up writing a simple camelizer myself.

private String toCamelCase(String value, boolean startWithLowerCase) {
	String[] strings = StringUtils.split(value.toLowerCase(), "_");
	for (int i = startWithLowerCase ? 1 : 0; i < strings.length; i++){
		strings[i] = StringUtils.capitalize(strings[i]);
	}
	return StringUtils.join(strings);
}

I guess this helpers covers most of the requirements. At least it is covering all that I need. As an alternative one could use the WordUtils#capitalizeFully() and postprocess the result.

The way back is even more difficult, because the delimiters for split() are a bit harder to determine. While many other programming languages feature a camelize and underscore method, Java (and Apache Commons) does not. Why? Should I propose a patch?

  • Facebook
  • Delicious
  • Digg
  • StumbleUpon
  • Mister Wong
  • Reddit
  • Instapaper
  • Technorati
  • Blogger
Fabian Lange

 

Weitere Beiträge aus dem codecentric Blog

2 Responses to StringUtils.camelize(String);

  1. I do believe that you should submit this idea to the Apache Software Foundation, even if it’s only a JIRA issue to begin with.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>