java基础之自定义注解

自定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
int id() default 0;

String name() default ;

}

使用注解:

package com.ck.wyy.basic.Annotation;
import java.lang.reflect.Field;

public class TestAnnotation{
public static void main(String[] args) throws ClassNotFoundException {
Class myAnnotation = Anno.class;
Field[] declaredFields = myAnnotation.getDeclaredFields();

    for (Field declaredField : declaredFields) {
        System.out.println(declaredField.getAnnotation(MyAnnotation.class).id());
    }
}

}

class Anno {
@MyAnnotation(id = 3)
public int id;
}

返回结果:

''
3

Process finished with exit code 0
''

注解的本质是反射

你可能感兴趣的:(java基础之自定义注解)