四、自定义注解

    技术2023-06-08  86

    自定义注解

    一、声明 格式: 【权限修饰符】 @interface 注解名{ }

    二、使用 @注解名

    三、读取: 特别说明如果需要用反射读取某个注解,这个注解声明的时候,一定要增加这个元注解@Retention(RetentionPolicy.RUNTIME)

    四、元注解 元注解:注解注解的注解,给注解加的注解,在注解声明时,在上面加的注解

    1、@Target 用来标记这个注解可以使用在XXX位置 这个位置由ElementType枚举的常量对象来指定。

    2、@Retention(xx) 作用:标记这个注解可以滞留到XX阶段 这个生命周期由RetentionPolicy枚举的常量对象来指定。SOURCE(源代码),CLASS(字节码阶段),RUNTIME(运行时) 没有加默认的注解的周期就是源代码阶段。

    3、@Documented 作用:标记这个注解是否可以被javadoc.exe读取到API中

    4、@Inherited 作用:标记这个注解是否是可以被子类继承

    import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; public class TestDefineAnnotation { public static void main(String[] args) { //下面的代码用到了反射的知识点,没有学到但是需要知道是什么意思能看懂 Class clazz = MyClass.class; MyAnnotation my = (MyAnnotation) clazz.getAnnotation(MyAnnotation.class); System.out.println(my); } } @MyAnnotation class MyClass{ @MyAnnotation private int i; @MyAnnotation public void test() { } } //(1)声明注解 @Target({ElementType.METHOD,ElementType.FIELD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation{ }
    Processed: 0.023, SQL: 9