ZUI易入门Android之注解的使用

元注解:元注解是-一种基本注解,但是它能够应用到其它的注解上面。
@Retention:注解的保留期
- RetentionPolicy.SOURCE 注解只在源码阶段保留,在编译器进行编译时它将
被丢弃忽视。。
. RetentionPolicy.CLASS注解只被保留到编译进行的时候,它并不会被加载到
JVM中。中
. RetentionPolicy.RUNTIME 注解可以保留到程序运行的时候,它会被加载进入
到JVM中,所以在程序运行时可以获取到它们。。
@Target:作用域
ElementTypeANNOTATION TYPE可以给一个注解进行注解
ElementType.CONSTRUCTOR可以给构造方法进行注解
ElementTypc.FIELD可以给属性进行注解.
ElementType.LOCAL VARIABLE可以给局部变量进行注解
ElementType.METHOD可以给方法进行注解
ElementTypePACKAGE可以给一-个 包进行注解
ElementType.PARAMETER可以给- - 个方法内的参數进行注解。
ElementTypeTYPE可以给一个类型进行注解,比如类、接口、枚举

第一步  自定义注解

@Retention(RUNTIME) //运行时 注解
@Target(TYPE) //类接口注解
public @interface ViewInject {
         int mainlayoutid() default-1;
}

第二步 使用注解

@ViewInject(mainlayoutid = R. layout. activity _main)
public class MainActivity extends BaseActivity {
}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
  super . onCreate( savedInstanceState);
  ViewInject annotation = this . getClass() . getAnnotation(ViewInject. class);
  if Cannotation != null) {
     int mainlayoutid = annotation. mainlayoutid();
     if (mainlayoutid > 0) {
           setContentVi ew(mainlayoutid);
     } else {
           throw new RuntimeException "mainlayoutid < 0");
     }
     } else {
          throw new RuntimeException(" annotation");
     }
}

另外在Android中注解可以定义常量

@IntDef({SHANGHAI,HANGZHOU,BEIJING,SHENZHEN})
public @interface MainConstantTool {
    int SHANGHAI = 0;
    int HANGZHOU = 1;
    int BEIJING = 2;
    int SHENZHEN = 3;
}

猜你喜欢

转载自blog.csdn.net/qq_27248989/article/details/106641813