Suche…


Einführung

Die Dokumentation für Java-Code wird häufig mit Javadoc erstellt . Javadoc wurde von Sun Microsystems erstellt, um API-Dokumentation im HTML-Format aus Java-Quellcode zu erstellen. Die Verwendung des HTML-Formats bietet die Möglichkeit, verwandte Dokumente miteinander zu verknüpfen.

Syntax

  • / ** - Start von JavaDoc für eine Klasse, ein Feld, eine Methode oder ein Paket
  • @author // Um ​​dem Autor der Klasse, des Interfaces oder der Aufzählung einen Namen zu geben. Es ist notwendig.
  • @version // Die Version dieser Klasse, Schnittstelle oder Enumeration. Es ist notwendig. Sie können Makros wie% I% oder% G% für Ihre Quellcodeverwaltungssoftware verwenden, um an der Kasse auszufüllen.
  • @param // Zeigt die Argumente (Parameter) einer Methode oder eines Konstruktors an. Geben Sie für jeden Parameter ein @param-Tag an.
  • @return // Um ​​die Rückgabetypen für nicht-ungültige Methoden anzuzeigen.
  • @exception // Zeigt an, welche Ausnahmen von der Methode oder vom Konstruktor ausgelöst werden könnten. Ausnahmen , die gefangen werden muss sollte hier aufgeführt werden. Wenn Sie möchten, können Sie auch diejenigen hinzufügen, die nicht abgefangen werden müssen, wie ArrayIndexOutOfBoundsException. Geben Sie eine @ Ausnahme für jede Ausnahme an, die ausgelöst werden kann.
  • @throws // Wie @exception.
  • @see // Links zu einer Methode, einem Feld, einer Klasse oder einem Paket. Verwenden Sie in Form von package.Class # etwas.
  • @since // Bei dieser Methode wurde ein Feld oder eine Klasse hinzugefügt. Zum Beispiel JDK-8 für eine Klasse wie java.util.Optional <T> .
  • @serial, @serialField, @serialData // Wird verwendet, um die serialVersionUID anzuzeigen.
  • @deprecated // Eine Klasse, eine Methode oder ein Feld als veraltet markieren. Ein Beispiel wäre java.io.StringBufferInputStream . Eine vollständige Liste der vorhandenen veralteten Klassen finden Sie hier .
  • {@link} // Ähnlich wie @see, kann jedoch mit benutzerdefiniertem Text verwendet werden: {@link #setDefaultCloseOperation (int closeOperation). Weitere Informationen finden Sie unter JFrame # setDefaultCloseOperation.
  • {@linkplain} // Ähnlich wie {@link}, jedoch ohne Code-Schriftart.
  • {@code} // Für wörtlichen Code, z. B. HTML-Tags. Zum Beispiel: {@code <html> </ html>}. Dies wird jedoch eine Monospace-Schriftart verwenden. Verwenden Sie {@literal}, um dasselbe Ergebnis ohne Monospace-Schriftart zu erhalten.
  • {@literal} // Wie {@code}, jedoch ohne die Monospaced-Schriftart.
  • {@value} // Zeigt den Wert eines statischen Feldes an: Der Wert von JFrame # EXIT_ON_CLOSE ist {@value}. Sie können auch mit einem bestimmten Feld verknüpfen: Verwendet den App-Namen {@value AppConstants # APP_NAME}.
  • {@docRoot} // Der Stammordner des JavaDoc-HTML-Objekts relativ zur aktuellen Datei. Beispiel: <a href="{@docRoot}/credits.html"> Credits </a>.
  • HTML ist erlaubt: <code> "Hi Cookies" .Substring (3) </ code>.
  • * / - Ende der JavaDoc-Deklaration

Bemerkungen

Javadoc ist ein im JDK enthaltenes Werkzeug, mit dem Kommentare im Code in eine HTML-Dokumentation konvertiert werden können. Die Java-API-Spezifikation wurde mit Javadoc erstellt. Dasselbe gilt für einen Großteil der Dokumentation von Drittanbieter-Bibliotheken.

Klassendokumentation

Alle Javadoc-Kommentare beginnen mit einem Blockkommentar gefolgt von einem Sternchen ( /** ) und enden, wenn der Blockkommentar dies tut ( */ ). Optional kann jede Zeile mit einem beliebigen Leerzeichen und einem einzelnen Stern beginnen. Diese werden bei der Erstellung der Dokumentationsdateien ignoriert.

/**
 * Brief summary of this class, ending with a period.
 *
 * It is common to leave a blank line between the summary and further details.
 * The summary (everything before the first period) is used in the class or package 
 * overview section.
 *
 * The following inline tags can be used (not an exhaustive list): 
 * {@link some.other.class.Documentation} for linking to other docs or symbols
 * {@link some.other.class.Documentation Some Display Name} the link's appearance can be 
 * customized by adding a display name after the doc or symbol locator
 * {@code code goes here} for formatting as code
 * {@literal <>[]()foo} for interpreting literal text without converting to HTML markup 
 * or other tags.
 *
 * Optionally, the following tags may be used at the end of class documentation 
 * (not an exhaustive list):
 *
 * @author John Doe
 * @version 1.0
 * @since 5/10/15
 * @see some.other.class.Documentation
 * @deprecated This class has been replaced by some.other.package.BetterFileReader
 * 
 * You can also have custom tags for displaying additional information.
 * Using the @custom.<NAME> tag and the -tag custom.<NAME>:htmltag:"context"
 * command line option, you can create a custom tag.
 *
 * Example custom tag and generation:
 * @custom.updated 2.0    
 * Javadoc flag: -tag custom.updated:a:"Updated in version:"
 * The above flag will display the value of @custom.updated under "Updated in version:"
 *
 */
public class FileReader {
}

Die gleichen Classes und Formate, die für Classes verwendet werden, können auch für Enums und Interfaces werden.

Methodendokumentation

Alle Javadoc-Kommentare beginnen mit einem Blockkommentar gefolgt von einem Sternchen ( /** ) und enden, wenn der Blockkommentar dies tut ( */ ). Optional kann jede Zeile mit einem beliebigen Leerzeichen und einem einzelnen Stern beginnen. Diese werden bei der Erstellung der Dokumentationsdateien ignoriert.

/**
 * Brief summary of method, ending with a period.
 *
 * Further description of method and what it does, including as much detail as is 
 * appropriate.  Inline tags such as
 * {@code code here}, {@link some.other.Docs}, and {@literal text here} can be used.
 *
 * If a method overrides a superclass method, {@inheritDoc} can be used to copy the 
 * documentation
 * from the superclass method
 *
 * @param stream Describe this parameter.  Include as much detail as is appropriate
 *               Parameter docs are commonly aligned as here, but this is optional.
 *               As with other docs, the documentation before the first period is 
 *               used as a summary.
 *
 * @return Describe the return values.  Include as much detail as is appropriate
 *         Return type docs are commonly aligned as here, but this is optional.
 *         As with other docs, the documentation before the first period is used as a 
 *         summary.
 *
 * @throws IOException Describe when and why this exception can be thrown.
 *                     Exception docs are commonly aligned as here, but this is 
 *                     optional.
 *                     As with other docs, the documentation before the first period 
 *                     is used as a summary.
 *                     Instead of @throws, @exception can also be used.
 *
 * @since 2.1.0
 * @see some.other.class.Documentation
 * @deprecated  Describe why this method is outdated. A replacement can also be specified.
 */
public String[] read(InputStream stream) throws IOException {
    return null;
}

Felddokumentation

Alle Javadoc-Kommentare beginnen mit einem Blockkommentar gefolgt von einem Sternchen ( /** ) und enden, wenn der Blockkommentar dies tut ( */ ). Optional kann jede Zeile mit einem beliebigen Leerzeichen und einem einzelnen Stern beginnen. Diese werden bei der Erstellung der Dokumentationsdateien ignoriert.

/**
 * Fields can be documented as well.
 * 
 * As with other javadocs, the documentation before the first period is used as a
 * summary, and is usually separated from the rest of the documentation by a blank 
 * line.
 * 
 * Documentation for fields can use inline tags, such as:
 * {@code code here}
 * {@literal text here}
 * {@link other.docs.Here}
 * 
 * Field documentation can also make use of the following tags:
 * 
 * @since 2.1.0
 * @see some.other.class.Documentation
 * @deprecated Describe why this field is outdated
 */
public static final String CONSTANT_STRING = "foo";

Paketdokumentation

Java SE 5

Es ist möglich, eine Dokumentation auf Paketebene in Javadocs mit einer Datei namens package-info.java . Diese Datei muss wie folgt formatiert sein. Führende Leerzeichen und Sternchen optional, normalerweise in jeder Zeile aus Gründen der Formatierung

/**
 * Package documentation goes here; any documentation before the first period will 
 * be used as a summary.
 *
 * It is common practice to leave a blank line between the summary and the rest
 * of the documentation; use this space to describe the package in as much detail
 * as is appropriate.
 * 
 * Inline tags such as {@code code here}, {@link reference.to.other.Documentation},
 * and {@literal text here} can be used in this documentation.
 */
package com.example.foo;

// The rest of the file must be empty.

In diesem Fall müssen Sie diese Datei package-info.java im Ordner des Java-Pakets com.example.foo .

Das Verknüpfen mit anderen Javadocs erfolgt mit dem @link Tag:

/**
 * You can link to the javadoc of an already imported class using {@link ClassName}.
 *
 * You can also use the fully-qualified name, if the class is not already imported: 
 *  {@link some.other.ClassName}
 *
 * You can link to members (fields or methods) of a class like so:
 *  {@link ClassName#someMethod()}
 *  {@link ClassName#someMethodWithParameters(int, String)}
 *  {@link ClassName#someField}
 *  {@link #someMethodInThisClass()} - used to link to members in the current class
 *  
 * You can add a label to a linked javadoc like so:
 *  {@link ClassName#someMethod() link text} 
 */

Screenshot des ersten Beispiels

Mit dem Tag @see können Sie dem Abschnitt Siehe auch Elemente hinzufügen. Wie @param oder @return der Ort, an dem sie erscheinen, nicht relevant. Die Spezifikation sagt, Sie sollten es nach @return schreiben.

/**
 * This method has a nice explanation but you might found further
 * information at the bottom.
 *
 * @see ClassName#someMethod()
 */

Screenshot des Beispiels

Wenn Sie Links zu externen Ressourcen hinzufügen möchten, können Sie einfach das HTML-Tag <a> . Sie können es überall oder innerhalb von @link und @see Tags verwenden.

/**
 * Wondering how this works? You might want
 * to check this <a href="http://stackoverflow.com/">great service</a>.
 *
 * @see <a href="http://stackoverflow.com/">Stack Overflow</a>
 */

Screenshot des Beispiels für externe Links

Javadocs über die Befehlszeile erstellen

Viele IDEs unterstützen das automatische Generieren von HTML aus Javadocs. Einige Build-Tools (z. B. Maven und Gradle ) verfügen auch über Plugins, die die HTML-Erstellung unterstützen.

Diese Tools sind jedoch nicht erforderlich, um den Javadoc-HTML-Code zu generieren. Dies kann mit dem Befehlszeilen- javadoc Tool ausgeführt werden.

Die grundlegendste Verwendung des Tools ist:

javadoc JavaFile.java

JavaFile.java wird HTML aus den Javadoc-Kommentaren in JavaFile.java .

Eine praktischere Anwendung des Befehlszeilentools, das rekursiv alle Java-Dateien in [source-directory] [package.name] , Dokumentation für [package.name] und alle [package.name] erstellt und den generierten HTML- [package.name] in das [docs-directory] [package.name] ist:

javadoc -d [docs-directory] -subpackages -sourcepath [source-directory] [package.name]

Inline-Code-Dokumentation

Neben der Javadoc-Dokumentation kann der Code auch inline dokumentiert werden.

Einzeilige Kommentare werden von // gestartet und dürfen nach einer Anweisung in derselben Zeile stehen, jedoch nicht vorher.

public void method() {
  
  //single line comment
  someMethodCall(); //single line comment after statement
  
}

Mehrzeilige Kommentare werden zwischen /* und */ . Sie können sich über mehrere Zeilen erstrecken und wurden sogar zwischen Anweisungen positioniert.

public void method(Object object) {
  
  /*
    multi 
    line 
    comment
  */
  object/*inner-line-comment*/.method(); 
}

JavaDocs sind eine spezielle Form von mehrzeiligen Kommentaren, beginnend mit /** .

Da zu viele Inline-Kommentare die Lesbarkeit von Code beeinträchtigen, sollten sie sparsam verwendet werden, falls der Code nicht selbsterklärend genug ist oder die Entwurfsentscheidung nicht offensichtlich ist.

Ein zusätzlicher Anwendungsfall für einzeilige Kommentare ist die Verwendung von TAGs, bei denen es sich um kurze, auf Konventionen basierende Schlüsselwörter handelt. Einige Entwicklungsumgebungen erkennen bestimmte Konventionen für solche Einzelkommentare an. Häufige Beispiele sind

  • //TODO
  • //FIXME

Oder geben Sie Referenzen aus, zB für Jira

  • //PRJ-1234

Codeausschnitte in der Dokumentation

Die kanonische Art, Code in der Dokumentation zu schreiben, ist mit dem {@code } . Wenn innerhalb von <pre></pre> mehrzeiliger Code-Wrap vorhanden ist.

/**
 * The Class TestUtils.
 * <p>
 * This is an {@code inline("code example")}.
 * <p>
 * You should wrap it in pre tags when writing multiline code.
 * <pre>{@code
 *  Example example1 = new FirstLineExample();
 *  example1.butYouCanHaveMoreThanOneLine();
 * }</pre>
 * <p>
 * Thanks for reading.
 */
class TestUtils {

Manchmal müssen Sie in den Javadoc-Kommentar etwas komplexen Code einfügen. Das @ -Zeichen ist besonders problematisch. Die Verwendung des alten <code> -Tags neben dem {@literal } löst das Problem.

/**
 * Usage:
 * <pre><code>
 * class SomethingTest {
 * {@literal @}Rule
 *  public SingleTestRule singleTestRule = new SingleTestRule("test1");
 *
 * {@literal @}Test
 *  public void test1() {
 *      // only this test will be executed
 *  }
 *
 *  ...
 * }
 * </code></pre>
 */
class SingleTestRule implements TestRule { }


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow