我有一个小代码示例,我想在Javadoc注释中包含一个方法。

/**
 * -- 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
 */

问题是在Javadoc中显示的代码示例没有换行符,这使得它难以阅读。

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

我想我假设代码标记可以处理换行符是错误的。在Javadoc注释中格式化代码示例的最佳方法是什么?


当前回答

我刚刚在这里阅读了Javadoc 1.5参考,只有<和>的代码必须包含在{@code…}中。这里有一个简单的例子:

 /** 
 * Bla bla bla, for example:
 *
 * <pre>
 * void X() {
 *    List{@code <String>} a = ...;
 *    ...
 * }
 * </pre>
 *
 * @param ...
 * @return ...
 */
 .... your code then goes here ...

其他回答

<blockquote><pre>…以前和< > {@code……前者将省略泛型中的类型声明,而后者将保留它。

例如: List<MyClass> myObject = null; List myObject = null;List<MyClass> myObject = null;第二种情况

用<pre></pre>标签将多行代码括起来。

我使用这两种方法没有任何问题:

<pre>
<code>
 ... java code, even including annotations
</code>
</pre>

and

<pre class="code">
 ... java code, even including annotations
</pre>

当然,后者更简单,请注意class="code"部分

/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/

<pre/>用于保存行。 {@code必须有自己的行 <blockquote/>只是用于缩进。

public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}

用JDK8更新

正确代码的最低要求是<pre/>和{@code}。

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

收益率

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

可选的括起来<blockquote/>插入缩进。

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

收益率

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

插入<p>或用<p>和</p>包围会产生警告。

试着用“pre”代替“code”。HTML中的pre标记将文本标记为预格式化,所有换行符和空格都将在您键入它们时显示。