Tuesday, May 25, 2010

I think this qualifies as a 'gotcha'

I was writing some Java code today. I'm writing a plug-in for Eclipse that will actually insert some Java annotations (e.g., @Override) into your code automatically.

Unfortunately, every time I ran my plug-in, the annotations were being inserted without the @ sign (e.g., Override). I couldn't figure out what was going on, looking at the code that generates the text:

String annotation_text = ...
StringBuilder sb = new StringBuilder('@');

Finally, I hovered over the StringBuilder constructor to figure out which constructor I was calling. Low and behold, I'm calling this one:
java.lang.StringBuilder.StringBuilder(int capacity)

In other words, by using single quotes, I am specifying the character '@' which is then implicitly cast to an int. Hmm... This doesn't seem so bad at first, but there's an asymmetry in the API. If I use this constructor:
new StringBuilder("@");
I get the behavior I expect, a string builder initialized to the at sign.

Moreover, there are append methods that take a single character:
Adds the single at sign character to the stream. So, knowing about this method, and the string constructor of the StringBuilder, I naturally assumed there was a character constructor as well... NOT SO FAST BECKMAN.

No comments:

Post a Comment