简体   繁体   中英

How will I know the annotations of a Java class?

I need to know the annotations of a Java class. I am using Lombok.

Sample is:

@Data
@Builder
public class JavaBean {}

I tried java.lang.annotation.Annotation[] annotation = JavaBean.class.getAnnotations but it doesn't show Data and Builder.

I think you cannot see the annotations in JavaBean.class.getAnnotations because the @Retention is equals to SOURCE.

This kind of annotation is not needed at runtime.

For more details : Annotation SOURCE Retention Policy

Have a good day.

The answer is in source of these annotations:

@Target({TYPE, METHOD, CONSTRUCTOR})
@Retention(SOURCE)
public @interface Builder {
.....

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Data {
.....

Your code to get annotation is correct but it's @Retention(RetentionPolicy.SOURCE) which is playing role here.

Java defined 3 types of retention policies through java.lang.annotation.RetentionPolicy enumeration. It has SOURCE , CLASS and RUNTIME .

1) Annotation with retention policy SOURCE will be retained only with source code, and discarded during compile time.

2) Annotation with retention policy CLASS will be retained till compiling the code, and discarded during runtime.

3) Annotation with retention policy RUNTIME will be available to the JVM through runtime.

@Data and @Builder are marked with @Retention(SOURCE) which means these annotations are not present at runtime with your class hence you are not able to get these annotations..

Lombok批注在实际编译之前进行了预处理,因此,已编译的类不包含它们作为批注,而是包含已生成的代码。

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