120

how can I make a javadoc link to a private field?

class Foo {
  private String bar;
  public String getBar() { return bar; }
}

{@link Foo#getBar()} works.

{@link Foo#bar} doesn't.

xlecoustillier
  • 16,183
  • 14
  • 60
  • 85
membersound
  • 81,582
  • 193
  • 585
  • 1,120
  • 9
    Why would you want to link javadoc to something final users won't be able to see ? – xlecoustillier Feb 10 '13 at 10:50
  • 1
    I often us @link for having the javadocs auto-renamed if I rename what is linked. So I thought if I rename "bar" sometime, the javadoc would autoupdate accordingly. – membersound Feb 10 '13 at 10:55
  • 6
    @X.L.Ant because it is good for you too, when you look next year on that private field, and have no idea what is was meant for. Especially when the javadoc of the public getter for that feiled only contains auto created javadoc comment: "getter method()" – AlexWien Feb 10 '13 at 15:57
  • 4
    @Mark the dupplicate you provided is another question, there the javadoc options are queried, here the javadoc tags in the code are asked – AlexWien Feb 10 '13 at 15:59
  • 1
    @AlexWien I agree on documenting private fields, but I'm not fond of exposing their documentation in the javadoc, as the dev which will use this class doesn't have to know its inner machinery. – xlecoustillier Feb 10 '13 at 19:18
  • Or we just do the opposite, javadoc the private field to indicate its usage? – WesternGun Sep 25 '18 at 08:17
  • @xlecoustillier, because at least a few developers have a chance to look at the source, either those who have access to closed source, or every developers in case of open source. Final users don't/can't read Javadoc, so they're irrelevant. – zakmck Jan 23 '23 at 15:33

2 Answers2

168

The syntax is fine, both the following work within a class (and there's no reason to link to a private field from a different class):

public class Demo {
  private int num = 0;
  /**
  * Access field {@link Demo#num} / {@link #num}  ...
  */
  private void foo() { ... }
...

When generating the javadoc, e.g., via ant, just specify that private fields should be included (the default minimum access is "protected", not "private"):

<target name="javadoc" depends="compile" description="gen javadoc">
  <javadoc destdir="build/docs"
           author="true"
           version="true"
           use="true"
           access="private"
           windowtitle="Demo API">

    <fileset dir="src/main" defaultexcludes="yes">
      <include name="com/**"/>
    </fileset>

    <doctitle><![CDATA[<h1>Test</h1>]]></doctitle>
    <link offline="true" href="http://download.oracle.com/javase/6/docs/api/" packagelistLoc="doc"/>
  </javadoc>
</target>
michael
  • 9,161
  • 2
  • 52
  • 49
7

I think what you are writing in the comments is fine, you just need to tell JavaDoc to also include private fields in the documentation. JavaDoc has an option -private for this. Check this answer.

Community
  • 1
  • 1
damix911
  • 4,165
  • 1
  • 29
  • 44