Xu Hướng 7/2022 # How To Write Doc Comments For The Javadoc Tool # Top View

Xem 6,534

Bạn đang xem bài viết How To Write Doc Comments For The Javadoc Tool được cập nhật mới nhất ngày 04/07/2022 trên website Ezlearning.edu.vn. Hy vọng những thông tin mà chúng tôi đã chia sẻ là hữu ích với bạn. Nếu nội dung hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Cho đến thời điểm hiện tại, bài viết này đã đạt được 6,534 lượt xem.

--- Bài mới hơn ---

  • Java: Đọc, Ghi Và Tạo Tập Tin
  • Hướng Dẫn Code Java: Lập Trình Java Cho Người Mới Bắt Đầu
  • Hướng Dẫn Lưu Nội Dung Có Dấu Tiếng Việt Trong File Text (*.txt)
  • Cách Sửa Lỗi Font Tiếng Việt Bị Lỗi Trên Notepad Đơn Giản
  • Hướng Dẫn Cách Viết Mẫu Email Xin Việc Chuẩn
  • Javadoc Home Page

    • For reference material on Javadoc tags, see the Javadoc reference pages.




    Writing API Specifications

    • The Java Platform API Specification is a contract between callers and implementations.

    • Unless otherwise noted, the Java API Specification assertions need to be implementation-independent. Exceptions must be set apart and prominently marked as such.

      We have guidelines for how to prominently document implementation differences.

    • The Java API Specification should contain assertions sufficient to enable Software Quality Assurance to write complete Java Compatibility Kit (JCK) tests.

    Writing Programming Guide Documentation

    Who Owns and Edits the Doc Comments


    API documentation (API docs) or API specifications (API specs)

    On-line or hardcopy descriptions of the API, intended primarily for programmers writing in Java. These can be generated using the Javadoc tool or created some other way. An API specification is a particular kind of API document, as described above. An example of an API specification is the on-line Java Platform, Standard Edition 7 API Specification.


    Source Files

    The Javadoc tool can generate output originating from four different types of “source” files:

    • Miscellaneous unprocessed files – these include images, sample source code, class files, applets, HTML files, and whatever else you might want to reference from the pvious files.

    For more details, see: Source Files.

    Writing Doc Comments

    Format of a Doc Comment

    /** * Returns an Image object that can then be painted on the screen. * The url argument must specify an absolute {@link URL}. The name * argument is a specifier that is relative to the url argument. * This method always returns immediately, whether or not the * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives * that draw the image will incrementally paint on the screen. * * @param url an absolute URL giving the base location of the image * @param name the location of the image, relative to the url argument * @return the image at the specified URL * @see Image */ public Image getImage(URL url, String name) { try { return getImage(new URL(url, name)); } catch (MalformedURLException e) { return null; } }


    • The resulting HTML from running Javadoc is shown below
    • Starting with Javadoc 1.4, the leading asterisks are optional.
    • Write the first sentence as a short summary of the method, as Javadoc automatically places it in the method summary table (and index).

    For more examples, see Simple Examples.

    Here is what the pvious example would look like after running the Javadoc tool:


    public Image getImage(URL url, String name)

    Returns an Image object that can then be painted on the screen. The url argument must specify an absolute URL. The name argument is a specifier that is relative to the url argument.

    This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.


    url – an absolute URL giving the base location of the image.

    name – the location of the image, relative to the url argument.


    the image at the specified URL.

    See Also:


    Also see Troubleshooting Curly Quotes (Microsoft Word) at the end of this document.

    Doc Comment Checking Tool

    DocCheck is a Javadoc doclet, or “plug-in”, and so requires that the Javadoc tool be installed (as part of the Java 2 Standard Edition SDK).


    First Sentence

    This sentence ends at the first period that is followed by a blank, tab, or line terminator, or at the first tag (as defined below). For example, this first sentence ends at “Prof.”:

    /** * This is a simulation of Prof. Knuth's MIX computer. */

    However, you can work around this by typing an HTML meta-character such as “&” or “<” immediately after the period, such as:

    /** * This is a simulation of Prof.&nbsp;Knuth's MIX computer. */


    /** */

    In particular, write summary sentences that distinguish overloaded methods from each other. For example:

    /** * Class constructor. */ foo() { ... /** * Class constructor specifying number of objects to create. */ foo(int n) { ...


    Write the description to be implementation-independent, but specifying such dependencies where necessary. This helps engineers write code to be “write once, run anywhere.”

    • Define clearly what is required and what is allowed to vary across platforms/implementations.
    • Ideally, make it complete enough for conforming implementors. Realistically, include enough description so that someone reading the source code can write a substantial suite of conformance tests. Basically, the spec should be complete, including boundary conditions, parameter ranges and corner cases.
    • Where appropriate, mention what the specification leaves unspecified or allows to vary among implementations.
    • On Windows systems, the path search behavior of the loadLibrary method is identical to that of the Windows API’s LoadLibrary procedure.

      The use of “On Windows” at the beginning of the sentence makes it clear up front that this is an implementation note.

    • When a method in a class overrides a method in a superclass
    • When a method in an interface overrides a method in a superinterface
    • When a method in a class implements a method in an interface

    In the first two cases, if a method m() overrides another method, The Javadoc tool will generate a subheading “Overrides” in the documentation for m(), with a link to the method it is overriding.

    In the third case, if a method m() in a given class implements a method in an interface, the Javadoc tool will generate a subheading “Specified by” in the documentation for m(), with a link to the method it is implementing.

    A Style Guide

      • Java keywords
      • package names
      • class names
      • method names
      • interface names
      • field names
      • argument names
      • code examples

    • Use in-line links economically

      You are encouraged to add links for API names (listed immediately above) using the

    • Omit parentheses for the general form of methods and constructors

      When referring to a method or constructor that has multiple forms, and you mean to refer to a specific form, use parentheses and argument types. For example, ArrayList has two add methods: add(Object) and add(int, Object):

      The add(int, Object) method adds an item at a specified position in this arraylist.

      However, if referring to both forms of the method, omit the parentheses altogether. It is misleading to include empty parentheses, because that would imply a particular form of the method. The intent here is to distinguish the general method from any of its particular forms. Include the word “method” to distinguish it as a method and not a field.

      The add method enables you to insert items. (pferred)

      The add() method enables you to insert items. (avoid when you mean “all forms” of the add method)

    • OK to use phrases instead of complete sentences, in the interests of brevity.

      This holds especially in the initial summary and in @param tag descriptions.

    • Use 3rd person (descriptive) not 2nd person (pscriptive).
    • The description is in 3rd person declarative rather than 2nd person imperative.

      Gets the label. (pferred)

      Get the label. (avoid)

    • Method descriptions begin with a verb phrase.
    • A method implements an operation, so it usually starts with a verb phrase:

      Gets the label of this button. (pferred)

      This method gets the label of this button.

    • Class/interface/field descriptions can omit the subject and simply state the object.
    • These API often describe things rather than actions or behaviors:

      A button label. (pferred)

      This field is a button label. (avoid)

    • Use “this” instead of “the” when referring to an object created from the current class.
    • For example, the description of the getToolkit method should read as follows:

      Gets the toolkit for this component. (pferred)

      Gets the toolkit for the component. (avoid)

    • Add description beyond the API name.

    Avoid – The description below says nothing beyond what you know from reading the method name. The words “set”, “tool”, “tip”, and “text” are simply repeated in a sentence.

    /** * Sets the tool tip text. * * @param text the text of the tool tip */ public void setToolTipText(String text) {

    Preferred – This description more completely defines what a tool tip is, in the larger context of registering and being displayed in response to the cursor.

    /** * Registers the text to display in a tool tip. The text * displays when the cursor lingers over the component. * * @param text the string to display. If the text is null, * the tool tip is turned off for this component. */ public void setToolTipText(String text) {

    • Be clear when using the term “field”.

      Be aware that the word “field” has two meanings:

    • static field, which is another term for “class variable”
    • text field, as in the TextField class. Note that this kind of field might be restricted to holding dates, numbers or any text. Alternate names might be “date field” or “number field”, as appropriate.
    • Avoid Latin
    • use “also known as” instead of “aka”, use “that is” or “to be specific” instead of “i.e.”, use “for example” instead of “e.g.”, and use “in other words” or “namely” instead of “viz.”

    Tag Conventions

    This section covers:

    Most of the following tags are specified in the Java Language Specification, First Edition. Also see the Javadoc reference page.

    Order of Tags

    Include tags in the following order:

    • @author (classes and interfaces only, required)
    • @version (classes and interfaces only, required. See footnote 1)
    • @param (methods and constructors only)
    • @return (methods only)
    • @exception (@throws is a synonym added in Javadoc 1.2)
    • @see
    • @since
    • @serial (or @serialField or @serialData)
    • @depcated (see How and When To Depcate APIs)

    Ordering Multiple Tags

    Multiple @author tags should be listed in chronological order, with the creator of the class listed at the top.

    Multiple @param tags should be listed in argument-declaration order. This makes it easier to visually match the list to the declaration.

    Multiple @throws tags (also known as @exception) should be listed alphabetically by the exception names.


    Multiple @see tags should be ordered as follows, which is roughly the same order as their arguments are searched for by javadoc, basically from nearest to farthest access, from least-qualified to fully-qualified, The following list shows this progression. Notice the methods and constructors are in “telescoping” order, which means the “no arg” form first, then the “1 arg” form, then the “2 arg” form, and so forth. Where a second sorting key is needed, they could be listed either alphabetically or grouped logically.

    @see #field @see #Constructor(Type, Type...) @see #Constructor(Type id, Type id...) @see #method(Type, Type,...) @see #method(Type id, Type, id...) @see Class @see Class#field @see Class#Constructor(Type, Type...) @see Class#Constructor(Type id, Type id) @see Class#method(Type, Type,...) @see Class#method(Type id, Type id,...) @see package.Class @see package.Class#field @see package.Class#Constructor(Type, Type...) @see package.Class#Constructor(Type id, Type id) @see package.Class#method(Type, Type,...) @see package.Class#method(Type id, Type, id) @see package

    Required Tags

    These principles expedite automated searches and automated processing. Frequently, too, the effort to avoid redundancy pays off in extra clarity.

    Tag Comments

    @author (reference page)

    You can provide one @author tag, multiple @author tags, or no @author tags. In these days of the community process when development of new APIs is an open, joint effort, the JSR can be consider the author for new packages at the package level. For example, the new package chúng tôi has “@author JSR-51 Expert Group” at the package level. Then inpidual programmers can be assigned to @author at the class level. As this tag can only be applied at the overview, package and class level, the tag applies only to those who make significant contributions to the design or implementation, and so would not ordinarily include technical writers.

    The @author tag is not critical, because it is not included when generating the API specification, and so it is seen only by those viewing the source code. (Version history can also be used for determining contributors for internal purposes.)

    If someone felt strongly they need to add @author at the member level, they could do so by running javadoc using the new 1.4

    -tag option:

    -tag author:a:"Author:"

    If the author is unknown, use “unascribed” as the argument to @author. Also see order of multiple @author tags.

    @version (reference page)

    The Java Software convention for the argument to the @version tag is the SCCS string “%I%, %G%”, which converts to something like ” 1.39, 02/28/97” (mm/dd/yy) when the file is checked out of SCCS.

    @param (reference page)

    The @param tag is followed by the name (not data type) of the parameter, followed by a description of the parameter. By convention, the first noun in the description is the data type of the parameter. (Articles like “a”, “an”, and “the” can pcede the noun.) An exception is made for the primitive int, where the data type is usually omitted. Additional spaces can be inserted between the name and description so that the descriptions line up in a block. Dashes or other punctuation should not be inserted before the description, as the Javadoc tool inserts one dash.

    Parameter names are lowercase by convention. The data type starts with a lowercase letter to indicate an object rather than a class. The description begins with a lowercase letter if it is a phrase (contains no verb), or an uppercase letter if it is a sentence. End the phrase with a period only if another phrase or sentence follows it.


    * @param ch the character to be tested * @param observer the image observer to be notified

    • When writing a phrase, do not capitalize and do not end with a period:
    • @param x  the x-coordinate, measured in pixels

    • When writing a phrase followed by a sentence, do not capitalize the phrase, but end it with a period to distinguish it from the start of the next sentence:
    • @param x  the x-coordinate. Measured in pixels.

    • If you pfer starting with a sentence, capitalize it and end it with a period:
    •   @param x  Specifies the x-coordinate, measured in pixels.

    • When writing multiple sentences, follow normal sentence rules:
    •   @param x  Specifies the x-coordinate. Measured in pixels.

    Also see order of multiple @param tags.

    @return (reference page)

    Omit @return for methods that return void and for constructors; include it for all other methods, even if its content is entirely redundant with the method description. Having an explicit @return tag makes it easier for someone to find the return value quickly. Whenever possible, supply return values for special cases (such as specifying the value returned when an out-of-bounds argument is supplied).

    Use the same capitalization and punctuation as you used in @param.

    @depcated (reference page)

    The @depcated description in the first sentence should at least tell the user when the API was depcated and what to use as a replacement. Only the first sentence will appear in the summary section and index. Subsequent sentences can also explain why it has been depcated. When generating the description for a depcated API, the Javadoc tool moves the @depcated text ahead of the description, placing it in italics and pceding it with a bold warning: “Depcated”. An @see tag (for Javadoc 1.1) or {@link} tag (for Javadoc 1.2 or later) should be included that points to the replacement method:

    • For Javadoc 1.2 and later, the standard format is to use @depcated tag and the in-line {@link} tag. This creates the link in-line, where you want it. For example:
    • /** * @depcated As of JDK 1.1, replaced by * {@link #setBounds(int,int,int,int)} */

    • For Javadoc 1.1, the standard format is to create a pair of @depcated and @see tags. For example:
    • /** * @depcated As of JDK 1.1, replaced by * setBounds * @see #setBounds(int,int,int,int) */

    If the member has no replacement, the argument to @depcated should be “No replacement”.

    Do not add @depcated tags without first checking with the appropriate engineer. Substantive modifications should likewise be checked first.

    @since (reference page)

    Specify the product version when the Java name was added to the API specification (if different from the implementation). For example, if a package, class, interface or member was added to the Java 2 Platform, Standard Edition, API Specification at version 1.2, use:

    /** * @since 1.2 */

    (The convention once was ” @since JDK1.2” but because this is a specification of the Java Platform, not particular to the Oracle JDK or SDK, we have dropped “JDK”.)

    When a package is introduced, specify an @since tag in its package description and each of its classes. (Adding @since tags to each class is technically not needed, but is our convention, as enables greater visibility in the source code.) In the absence of overriding tags, the value of the @since tag applies to each of the package’s classes and members.

    When a class (or interface) is introduced, specify one @since tag in its class description and no @since tags in the members. Add an @since tag only to members added in a later version than the class. This minimizes the number of @since tags.

    If a member changes from protected to public in a later release, the @since tag would not change, even though it is now usable by any caller, not just subclassers.

    @throws (@exception was the original tag) (reference page)

    A @throws tag should be included for any checked exceptions (declared in the throws clause), as illustrated below, and also for any unchecked exceptions that the caller might reasonably want to catch, with the exception of NullPointerException. Errors should not be documented as they are unpdictable. For more details, please see Documenting Exceptions with the @throws Tag.

    /** * @throws IOException If an input or output * exception occurred */ public void f() throws IOException { }

    See the Exceptions chapter of the Java Language Specification, Second Edition for more on exceptions. Also see order of multiple @throws tags.

    @see (reference page)

    Also see order of multiple @see tags.




    (All added in Javadoc 1.2) (reference page)

    For information about how to use these tags, along with an example, see “Documenting Serializable Fields and Data for a Class,” Section 1.6 of the Java Object Serialization Specification. Also see Oracle’s criteria for including classes in the serialized form specification.

    {@link} (Added in Javadoc 1.2) (reference page)

    For conventions, see Use In-Line Links Economically.

    Custom Tags and Annotations

    If annotations are new to you, when you need to markup your source code, it might not be immediately clear whether to use an annotation or a Javadoc custom tag. Here is a quick comparison of the two.

    In general, if the markup is intended to affect or produce documentation, it should probably be a javadoc tag; otherwise, it should be an annotation.

    • Tag – Intended as a way of adding structure and content to the documentation. Allows multi-line text to be provided. (Use the -tag or -taglet Javadoc option to create custom tags.) Tags should never affect program semantics.
    • Annotation – Does not directly affect program semantics, but does affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time. Allows a single line of text to be provided.

    Documenting Default Constructors

    Section 8.8.7 of the Java Language Specification, Second Edition describes a default constructor: If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided. It invokes the superclass constructor with no arguments. The constructor has the same access as its class.

    /** * Sole constructor. (For invocation by subclass * constructors, typically implicit.) */ protected AbstractMap() { }

    Documenting Exceptions with @throws Tag

    NOTE – The tags @throws and @exception are synonyms.

    Documenting Exceptions in API Specs

    The API specification for methods is a contract between a caller and an implementor. Javadoc-generated API documentation contains two ways of specifying this contract for exceptions — the “throws” clause in the declaration, and the @throws Javadoc tag. These guidelines describe how to document exceptions with the @throws tag.

    Throws Tag

    The purpose of the @throws tag is to indicate which exceptions the programmer must catch (for checked exceptions) or might want to catch (for unchecked exceptions).

    Guidelines – Which Exceptions to Document

    Document the following exceptions with the @throws tag:

    • All checked exceptions.

      (These must be declared in the throws clause.)

    • Those unchecked exceptions that the caller might reasonably want to catch.

      (It is considered poor programming practice to include unchecked exceptions in the throws clause.)

      Documenting these in the @throws tag is up to the judgment of the API designer, as described below.

    Documenting Unchecked Exceptions

    It is generally desirable to document the unchecked exceptions that a method can throw: this allows (but does not require) the caller to handle these exceptions. For example, it allows the caller to “translate” an implementation-dependent unchecked exception to some other exception that is more appropriate to the caller’s exported abstraction.

    Since there is no way to guarantee that a call has documented all of the unchecked exceptions that it may throw, the programmer must not depend on the psumption that a method cannot throw any unchecked exceptions other than those that it is documented to throw. In other words, you should always assume that a method can throw unchecked exceptions that are undocumented.

    Note that it is always inappropriate to document that a method throws an unchecked exception that is tied to the current implementation of that method. In other words, document exceptions that are independent of the underlying implementation. For example, a method that takes an index and uses an array internally should not be documented to throw an ArrayIndexOutOfBoundsException, as another implementation could use a data structure other than an array internally. It is, however, generally appropriate to document that such a method throws an IndexOutOfBoundsException.

    Keep in mind that if you do not document an unchecked exception, other implementations are free to not throw that exception. Documenting exceptions properly is an important part of write-once, run-anywhere.

    Background on Checked and Unchecked Exceptions

    The idea behind checking an exception is that the compiler checks at compile-time that the exception is properly being caught in a try-catch block.

    You can identify checked and unchecked exceptions as follows.

    • Unchecked exceptions are the classes RuntimeException, Error and their subclasses.
    • All other exception subclasses are checked exceptions.

    Note that whether an exception is checked or unchecked is not defined by whether it is included in a throws clause.

    Background on the Throws Clause

    Checked exceptions must be included in a throws clause of the method. This is necessary for the compiler to know which exceptions to check. For example (in java.lang.Class):


    public static Class forName(String className) throws ClassNotFoundException

    java.lang.Byte source code:


    public static Byte valueOf(String s, int radix) throws NumberFormatException

    Note that the Java Language Specification also shows unchecked exceptions in throws clauses (as follows). Using the throws clause for unchecked exceptions in the spec is merely a device meant to indicate this exception is part of the contract between the caller and implementor. The following is an example of this (where “final” and “synchronization” are removed to make the comparison simpler).

    java.util.Vector source code:

    public Object elementAt(int index)

    java.util.Vector spec in the Java Language Specification, 1st Ed. (p. 656):


    public Object elementAt(int index) throws IndexOutOfBoundsException

    Package-Level Comments

    The Javadoc tool processes package.html by doing three things:

    1. Processes any @see, @since or {@link} Javadoc tags that are psent.
    2. Copies the first sentence to the right-hand column of the

      Overview Summary .

    Template for chúng tôi source file

    Contents of chúng tôi source file

    • Make the first sentence a summary of the package. For example: “Provides classes and interfaces for handling text, dates, numbers and messages in a manner independent of natural languages.”
    • Describe what the package contains and state its purpose.
    • Package Specification

      • Include a description of or links to any package-wide specifications for this package that are not included in the rest of the javadoc-generated documentation. For example, the chúng tôi package might describe how the general behavior in that package is allowed to vary from one operating system to another (Windows, Solaris, Mac).
      • An assertion is a statement a conforming implementor would have to know in order to implement the Java platform.

        On that basis, at Oracle, references in this section are critical to the Java Compatibility Kit (JCK). The Java Compatibility Kit includes a test to verify each assertion, to determine what passes as Java Compatible. The statement “Returns an int” is an assertion. An example is not an assertion.

        Some “specifications” that engineers have written contain no assertions not already stated in the API specs (javadoc) — they just elaborate on the API specs. In this respect, such a document should not be referred to in this section, but rather should be referred to in the next section.

      • Include specific references. If only a section of a referenced document should be considered part of the API spec, then you should link or refer to only that section and refer to the rest of the document in the next section. The idea is to clearly delineate what is part of the API spec and what is not, so the JCK team can write tests with the proper breadth. This might even encourage some writers to break documents apart so specs are separate.

    • Related Documentation

      • Include references to any documents that do not contain specification assertions, such as overviews, tutorials, examples, demos, and guides.

    • Class and Interface Summary
  • Web hay
  • Links hay
  • Push
  • Chủ đề top 10
  • Chủ đề top 20
  • Chủ đề top 30
  • Chủ đề top 40
  • Chủ đề top 50
  • Chủ đề top 60
  • Chủ đề top 70
  • Chủ đề top 80
  • Chủ đề top 90
  • Chủ đề top 100
  • Bài viết top 10
  • Bài viết top 20
  • Bài viết top 30
  • Bài viết top 40
  • Bài viết top 50
  • Bài viết top 60
  • Bài viết top 70
  • Bài viết top 80
  • Bài viết top 90
  • Bài viết top 100
  • CẦM ĐỒ TẠI F88