java基础之自定义注解

2020-09-08  本文已影响0人  Let_Just_Do_it

自定义注解

@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
''

注解的本质是反射

上一篇下一篇

猜你喜欢

热点阅读