tags:

views:

5138

answers:

4

I have a small code example I want to include in the Javadoc comment for a method.

/**
 * -- ex: looping through List of Map objects --
 * <code>
 * for (int i = 0; i < list.size(); i++) {
 *      Map map = (Map)list.get(i);
 *      System.out.println(map.get("wordID"));
 *      System.out.println(map.get("word"));
 * }
 * </code>
 * 
 * @param query - select statement
 * @return List of Map objects
 */

The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.

-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); } 
Parameters
query - - select statement 
Returns:
List of Map objects

I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ?

+5  A: 

Enclose your multiline code with <pre></pre> tags.

Zach Scrivena
A: 

Try replacing "code" with "pre". The pre tag in HTML marks the text as preformatted and all linefeeds and spaces will appear exactly as you type them.

Edwin
+3  A: 

The java source has lots of good examples for this. Here's an example from the head of "String.java":

....
 * is equivalent to:
 * <p><blockquote><pre>
 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 * </pre></blockquote><p>
 * Here are some more examples of how strings can be used:
 * <p><blockquote><pre>
 *     System.out.println("abc");
 *     String cde = "cde";
 *     System.out.println("abc" + cde);
 *     String c = "abc".substring(2,3);
 *     String d = cde.substring(1, 2);
 * </pre></blockquote>
...
Steve B.
+24  A: 

In addition to the already mentioned <pre> tags, you should also use the @code JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:

* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>

Will give correct HTML output:

Set<String> s;
System.out.println(s);

While omitting the @code block (or using a <code> tag) will result in HTML like this:

Set s;
System.out.println(s);
Fabian Steeg
{@code } will do the <pre/> for you, IIRC.
Tom Hawtin - tackline
I would have thought so too, but unfortunately it doesn't, you still need to add the <pre> tag to get line breaks.
Fabian Steeg
Unfortunately, it seems when you hit ctrl+shift+F (Format code in Eclipse), Eclipse messes up the {@code} tag and replaces it with {@code ...
jpdaigle
@jpdaigle I just tried this in Eclipse Galileo and Helios and the formatter does not replace anything for me (on Mac OS, but I have never seen the formatter do anything like that on other platforms either).
Fabian Steeg