如何在javadoc中引用方法?例子标签类型擦除和#member

2022-08-31 04:00:09

如何使用标记链接到方法?@link

我想更改:

/**
 * Returns the Baz object owned by the Bar object owned by Foo owned by this.
 * A convenience method, equivalent to getFoo().getBar().getBaz()
 * @return baz
 */
public Baz fooBarBaz()

自:

/**
 * Returns the Baz object owned by the Bar object owned by Foo owned by this.
 * A convenience method, equivalent to {@link getFoo()}.{@link getBar()}.{@link getBaz()}
 * @return baz
 */
public Baz fooBarBaz()

但我不知道如何正确格式化标签。@link


答案 1

您可以在标准 Doclet 的文档注释规范中找到有关 JavaDoc 的大量信息,包括

{@link模块/包.class#成员标签}

标记之间(您要查找的标记)。文档中的相应示例如下

例如,下面是一个引用 getComponentAt(int, int) 方法的注释:

Use the {@link #getComponentAt(int, int) getComponentAt} method.

如果引用的方法位于当前类中,则可以省略该部件。module/package.class


关于JavaDoc的其他有用链接是:


答案 2

javadoc 文档@link部分的一般格式是:

{@link package.class#member label}

例子

同一类中的方法:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

不同类中的方法,可以在同一包中,也可以导入:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

方法位于其他包且未导入:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

链接到方法的标签,采用纯文本而不是代码字体:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

一连串的方法调用,如您的问题所示。我们必须为指向此类之外的方法的链接指定标签,否则我们得到 .但是在重构过程中,这些标签可能很脆弱 - 请参阅下面的“标签”。getFoo().Foo.getBar().Bar.getBaz()

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

标签

自动重构可能不会影响标签。这包括重命名方法,类或包;并更改方法签名。

因此,仅当需要与默认文本不同的文本时,提供标签。

例如,您可以从人类语言链接到代码:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

或者,您可以从代码示例中链接文本与默认值不同的文本,如上面的“方法调用链”下所示。但是,在 API 不断发展时,这可能很脆弱。

类型擦除和#member

如果方法签名包括参数化类型,请在 javadoc @link中使用这些类型的擦除。例如:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }