简体   繁体   中英

How can I add javadoc to a static initializer in Java?

I have refactored a class and moved some code from the constructor to a static initializer. What should I do with the javadoc that was on the constructor? Is it possible to add javadoc to a static initializer?

JavaDoc is intended primarily to document the interface of the class. JavaDoc comments must precede a class, field, constructor or method declaration.

A static initializer is not part of the interface. It's part of the implementation of the class.

You could document its behavior in the class documentation, if desired.

First and foremost, it's arguable if static initializers are good practice to start with.

If you decide to use them nevertheless, I'd add the documentation to the JavaDoc at the class level . Static initializers can, depending on how they're implemented, cause side-effects. If you use static initializers with side-effects, the behaviour should be documented for the consumer of said class.

I'd say the important parts of that documentation should be moved to the class' documentation:

/**
 * Your text here.
 */
public class SomeClass {
   static {
      /* your static initalizer */
   }
}

There is no such thing as a static constructor in Java ( as oposed to C# ), which is why you must document this behavior at the class level.

Also, since the static initializer will most likely initialize some static fields, if these fields are public, protected(, or package-private, depending on your JavaDoc visibility convention), you shold add details about the way these fields are initialized based on the behavior of the static initializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM