Search code examples
javacommentsjavadocmultiline

Is it possible to nest javadoc?


I want to nest javadoc in order to demonstrate some code functionality. However, the end of the inner javadoc comment block ends the outer comment block too.

Sample use case

/**
 * Sample is a utility for doing interesting stuff.
 * For example, you might use it this way:
 * 
 * <pre>{@code
 * /**
 *  * We write an Example class
 *  */
 * class Example {
 *     /**
 *      * This function does something.
 *      */
 *     void foo() {
 *         // ...
 *     }
 * 
 *     /**
 *      * This one does something else
 *      */
 *     void bar() {
 *         // ...
 *     }
 * 
 *     /**
 *      * now I'm gonna demonstrate something by calling foo() and bar() in this main method
 *      */
 *     public static void main(String[] args) {
 *         // ...
 *         foo();
 *         // ...
 *         bar();
 *         // ...
 *         // and now the kicker:
 *         Sample.baz();
 *         // everyone stands up and claps
 *         // ...
 *     }
 * }
 * }</pre>
 */
public class Sample {
    /**
     * Really cool thing that Sample does
     */
    static void baz() {
        // ...
    }
}

subpar solution

So I could try escaping the offending closing tags, but that shows up in the javadoc which is pretty ugly.

/**
 * outer doc
 * <pre>{@code
 * /**
 *  * inner doc
 *  *\/
 * }
 * </pre>
 */
public class Sample {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

yields

outer doc

 /**
  * inner doc
  *\/

Solution

  • I personally would remove {@code and would just use HTML entities where necessary:

    /**
     * Sample is a utility for doing interesting stuff.
     * For example, you might use it this way:
     * 
     * <pre>
     * /**
     *  * We write an Example class
     *  *&#x2f;
     * class Example {
     *     /**
     *      * This function does something.
     *      *&#x2f;
     *     void foo() {
     *         // ...
     *     }
     * 
     *     /**
     *      * This one does something else
     *      *&#x2f;
     *     void bar() {
     *         // ...
     *     }
     * 
     *     /**
     *      * now I'm gonna demonstrate something by calling foo() and bar() in this main method
     *      *&#x2f;
     *     public static void main(String[] args) {
     *         // ...
     *         foo();
     *         // ...
     *         bar();
     *         // ...
     *         // and now the kicker:
     *         Sample.baz();
     *         // everyone stands up and claps
     *         // ...
     *     }
     * }
     * </pre>
     */
    

    This will also require escaping @, <, >, and & as well, if they appear in your example javadoc. @ would be escaped as &#x40;, < is &lt;, > is &gt;, and & is &amp;.