Skip to main content

Extends javadoc with custom tags like @example.

Posted by survivant on November 8, 2009 at 5:14 AM PST

I would like to show you how you could extend your javadoc to include samples directly into the javadoc without extra work.

What I don't like about javadoc is the lack of code sample. Something is can be hard to find the starting point of a new framework.

Let's show a example, it will be easier to understand, and so simple.

[prettify]
 /** 
 *
 * This in a javadoc with a custom tag @example.
 *
 * @author Sebastien Dionne
 *
 * @example.
 * <pre>
 * 
 * SSDPControler controler = new SSDPControler();
 * 
 * // sends messages each 30 seconds.
 * controler.getPeriodicMessageSender().setDelay(30000);
 *
 * controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) {
 *     @Override
 *     public List<String> returnHellos() {
 *         List<String> list = new ArrayList<String>();
 *
 *         list.add("hello1");
 *         list.add("hello2");
 *
 *         return list;
 *     }
 * });
 * controler.start();
 * </pre>
 */
[/prettify]

In this example, we used a custom tag @example. The result will look like this.

[prettify]
...
public class SSDPControler
extends Object
implements ISSDPControler
...
This in a javadoc with a custom tag @example.

Example :

    SSDPControler controler = new SSDPControler();
 
    // sends messages each 30 seconds.
    controler.getPeriodicMessageSender().setDelay(30000);
 
    controler.setPeriodicMessageSender(new SSDPPeriodicMessageSender(null) {
       @Override
       public List<String> returnHellos() {
           List<String> list = new ArrayList<String>();
  
           list.add("hello1");
           list.add("hello2");
  
           return list;
       }
   });
   controler.start();
[/prettify]

There is a thing that you need to know to avoid surprises :

Javadoc tool will cut the custom tag as soon as it detect another annotation, so don't forget to convert to HTML code like
@ : become : "&"#64;

To acheive that you need to add little config into your pom. Add the lines in bold.

[prettify]
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-javadoc-plugin</artifactId>
    <version>2.6.1</version>
    <configuration>
          <links>
            <link>http://java.sun.com/javase/6/docs/api/</link>
          </links>
          <detectOfflineLinks/> 
          
          <tags>
            <tag>
              <name>example.</name>
              <placement>aoptcmf</placement>
              <head>Example :</head>
            </tag>
          </tags>
          
      </configuration>
</plugin>
[/prettify]