In this post, I am going to explain how to format various code snippets in Javadoc.
a. Using <pre> tag
b. Using <code> tag
c. Using {@code}
d. Using <pre> + {@code}
Using <pre> tag
<pre> tag defines the preformatted text, the content in <pre> tag preserves both spaces and line break.
Example
/**
* Resource module provides a method to get a Resource instance.
*
* <pre>
* Resource resource = Resource.create();
* resource.text();
* resource.close();
* </pre>
*
* @author Krishna
*
*/
public interface Resource extends AutoCloseable {
}
Above snippet generate below Javadoc.
Using <code> tag
Indentation and line breaks are lost in the <code> block. Special characters like '@', '<' and '>' have to be escaped with HTML codes.
/**
* Resource module provides a method to get a Resource instance.
*
* <code>
* Resource resource = Resource.create();
* resource.text();
* resource.close();
* </code>
*
* @author Krishna
*
*/
public interface Resource extends AutoCloseable {
}
Above snippet generate below Javadoc.
Using {@code}
{@code} tag is introduced in Java1.5 to document the code snippets. Code embedded inside {@code} tag will display correctly, but the indentation and line breaks will be lost.
/**
* Resource module provides a method to get a Resource instance.
*
* {@code
* Resource resource = Resource.create();
* resource.text();
* resource.close();
* }
*
* @author Krishna
*
*/
public interface Resource extends AutoCloseable {
}
Above snippet generate below Javadoc.
Using <pre> + {@code}
By combining <pre> + {@code} we can
a. Keep line breaks and spaces
b. Keep special characters
/**
* Resource module provides a method to get a Resource instance.
*
* <pre>
* {@code
* Resource resource = Resource.create();
* resource.text();
* resource.close();
* }
* </pre>
* @author Krishna
*
*/
public interface Resource extends AutoCloseable {
}
Above snippet generate below javadoc.
Points to note
a. Use <pre>...</pre> for multi-line java code snippets
b. Use {@code} for inline code snippets
c. Use <pre>{@code ... }</pre>, when you have some markup code like XML, HTML etc.,
No comments:
Post a Comment