ChatGPT解决这个技术问题 Extra ChatGPT

@Documented annotation in java

What's the purpose of @Documented annotation in java?

I saw the documentation, but could not get much from it. Can someone point out with the help of an clear example


C
Community

@Documented is a meta-annotation. You apply @Documented when defining an annotation, to ensure that classes using your annotation show this in their generated JavaDoc. I've not seen much use of it, but there is an example here. An earlier question suggests that it doesn't work automatically in Eclipse, but I've tested in Eclipse 3.6, and my annotations appear in the JavaDoc popups whether or not I attach the @Documented annotation to them.

Here's an example from Spring, which ensures that transactional methods are marked as such in the JavaDoc:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {

G
Gangnus

If some our annotation (for example, @InWork) is @Documented, then for every class having that @InWork annotation the text generated by javadoc will contain @InWork text, as a reference to the annotation.

Annotation:

@Documented
@Inherited  // for descenders of the annotation to have the @Documented feature automatically
@Retention(RetentionPolicy.RUNTIME) // must be there
public @interface InWork {
    String value();
}

Annotated target:

/**
 * Annotated class.
 */
@InWork(value = "")
public class MainApp {...}

The javadoc text:

https://i.stack.imgur.com/QLm1F.png

So, you have to decide, if the annotation should be shown in the javadoc text, and if yes, set @Documented to it.

The information above is taken from Oracle documentation.

Please, notice, that in Eclipse you'll see in javadoc generated text ALL annotations, are they @Documented, or not.

It is still correct for 4.3 version.


S
Sithsu

I found a useful page in the Java Tutorials which gives examples and more explanation for a number of standard annotations, including one use of @Documented. Specifically, look at the Note block at the bottom for the Preamble example (section Documentation).