软件编程
位置:首页>> 软件编程>> java编程>> Java元注解Retention代码示例介绍

Java元注解Retention代码示例介绍

作者:niuyongzhi  发布时间:2023-10-21 02:32:32 

标签:Java,Retention,元注解

1.注解声明:通过@interface就可以声明一个注解。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
   int value();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Get {
   String value() default "";
}
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Queue {
   String value() ;
}

2. @Target 元注解,注解的注解,它的取值定义在ElementType枚举类中。

@Target注解 用来定义我们自定义注解代码的什么位置。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface Target {
   ElementType[] value();
}

1)ElementType.FIELD 使用在成员变量上。

2)ElementType.METHOD 使用在成员方法上。

3)ElementType.PARAMETER 使用在方法参数上。

4)ElementType.TYPE 使用在类、接口上。

5)ElementType.ANNOTATION_TYPE 使用在注解上。

3.@Retention 元注解,取值定义在RetentionPolicy枚举类中。

用来定义注解生效的阶段:

1)SOURCE:注解只在源码阶段有效,不会编译到字节码中。

2)CLASS:注解在源码、字节码阶段有效,运行阶段不存在。

3)RUNTIME:注解在源码、字节码、运行阶段有效,也是最长用的。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.ANNOTATION_TYPE})
public @interface Retention {
   RetentionPolicy value();
}
public enum RetentionPolicy {
   SOURCE,
   CLASS,
   RUNTIME;
   private RetentionPolicy() {
   }
}

2.注解的使用

@BindView(R.id.start_activity)
   TextView startTextView;
@Get("http://www.baidu.com")
   Call getPerson(@Queue("name") String name,@Queue("200")int price);
   @Get("http://www.baidu.com")
   Call getPerson();

注解的使用很简单。

注解单独存在没有任何意义,必须配合其他技术。

应用:

1)注解+Apt注解处理器,生产java代码 ,databinding、butterknife、dagger2 hilt

2)注解+代码埋点

3)注解+反射+ * retrofit xUtils lifecycle

以上应用会在后面的文章继续分享。如果通过反射来获取注解上的值,Retrofit框架原理。

来源:https://blog.csdn.net/niuyongzhi/article/details/125837112

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com