Multiple line code example in Javadoc comment Multiple line code example in Javadoc comment java java

Multiple line code example in Javadoc comment


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);

For reference, a full list of tag descriptions available in Java SE 8 can be found here.


I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:

  • usage of old <code> - tag to prevent the curly brackets from being interpreted
  • usage of "new" {@code ...} - tag to get the generics included in the output
  • escaping of the @ sign in @Override via "{@literal @}Override" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket
  • remove one space in front of {@code and {@literal, to compensate inner spaces and keep the alignment

javadoc code:

/** this methods adds a specific translator from one type to another type. `  * i.e.  * <pre>  * <code>new BeanTranslator.Builder()  *   .translate(  *     new{@code Translator<String, Integer>}(String.class, Integer.class){  *      {@literal @}Override  *       public Integer translate(String instance) {  *         return Integer.valueOf(instance);  *       }})  *   .build();  * </code>  * </pre>  * @param translator  */

gets printed as

new BeanTranslator.Builder()  .translate(    new Translator<String, Integer>(String.class, Integer.class){      @Override      public Integer translate(String instance) {        return Integer.valueOf(instance);      }})  .build();


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>...