注解入门

作者: Chase_stars | 来源:发表于2019-08-26 21:51 被阅读12次

一个人有无成就,取决于他青年时期是不是有志气。 — 谢觉哉

写在前面

注解是从Java1.5版本引入的, 本篇文章就介绍注解以及如何自定义注解。

首先需要认识以下注解:

  • @Documented:是否要将注解信息添加到Java文档中。
  • @Retention:注解的生命周期。
  • @Target:注解的使用范围。
  • @Inherited:定义注解与子类的关系,在继承情况下默认是不会继承注解的,除非是使用@Inherited声明的注解,但只对类有效,对方法/属性无效。

生命周期

@Retention注解是用来声明注解的生命周期的,那么就看看它都有哪些生命周期可用。

/**
 * Annotation retention policy.  The constants of this enumerated type
 * describe the various policies for retaining annotations.  They are used
 * in conjunction with the {@link Retention} meta-annotation type to specify
 * how long annotations are to be retained.
 *
 * @author  Joshua Bloch
 * @since 1.5
 */
public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

以上代码就是@Retention注解可用的生命周期,它是一个枚举类,可用的生命周期有三种:

  • SOURCE:在编译时丢弃,也就是说在编译结束后这个注解将没有任何意义,不会写入字节码。
  • CLASS:在类加载时丢弃,也就是说在类加载结束后这个注解的信息将被写入字节码,是默认的生命周期。
  • RUNTIME:永远不会被丢弃,始终存在于运行时,可以通过反射机制读取注解信息。

使用范围

@Target注解是用来声明注解的使用范围的,那么就看看它都可以声明在哪些类型上。

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

以上代码就是@Target注解可声明的范围,它也是一个枚举类,可用的声明范围目前有十种:

  • TYPE:用于描述类、接口(包括注解类型) 或enum声明 Class。
  • FIELD:用于描述域(属性)。
  • METHOD:用于描述方法。
  • PARAMETER:用于描述参数。
  • CONSTRUCTOR:用于描述构造器。
  • LOCAL_VARIABLE:用于描述局部变量。
  • ANNOTATION_TYPE:用于描述注解类。
  • PACKAGE:用于描述包。
  • TYPE_PARAMETER:用来标注类型参数。
  • TYPE_USE:能标注任何类型名称。

注意:不使用@Target声明的注解可以声明在任何地方。

如何使用

下面通过一个例子来认识注解:

在Android应用开发中,难免要在Activity中使用setContentView和findViewById,一旦布局中的View很多,就要写好多好多的findViewById,导致代码很多,阅读性差。注解的出现帮助我们解决了这个问题,可以通过自定义注解减少findViewById代码,提升阅读性。

1.自定义注解

首先定义两个自定义注解,一个的使用范围是TYPE,作于在类上用于setContentView;另一个的使用范围是FIELD,作用在属性上用于findViewById;这两个注解的生命周期都是RUNTIME。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface BindLayout {

    int layoutId() default 0;
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BindView {

    int viewId() default 0;
}
2.读取注解信息

现在创建一个辅助类,只需要传入Activity即可,通过反射机制读取注解信息,将读取到不同的注解信息进行setContentView和findViewById。

public class AnnotationBinder {

    public static void bindLayout(Activity activity) {
        if (activity == null) {
            return;
        }

        if (activity.getClass().isAnnotationPresent(BindLayout.class)) {
            BindLayout bindLayout = activity.getClass().getAnnotation(BindLayout.class);
            activity.setContentView(bindLayout.layoutId());
        }
    }

    public static void bindView(Activity activity) {
        if (activity == null) {
            return;
        }

        Field[] fields = activity.getClass().getFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.isAnnotationPresent(BindView.class)) {
                    BindView bindView = field.getAnnotation(BindView.class);
                    try {
                        field.setAccessible(true);
                        field.set(activity, activity.findViewById(bindView.viewId()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
3.创建布局

写一个仅有两个按钮的布局。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击我 !!!"
        app:layout_constraintBottom_toBottomOf="@+id/btn_bottom"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击我 !!!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/btn_top" />

</android.support.constraint.ConstraintLayout>
4.创建Activity

下面要在Activity中使用自定义注解了,只需在需要的地方声明注解传入相应的值即可,调用 AnnotationBinder.bindLayout(this)就会自动setContentView,调用AnnotationBinder.bindView(this)就会自动findViewById。

@BindLayout(layoutId = R.layout.activity_main )
public class MainActivity extends AppCompatActivity {

    @BindView(viewId = R.id.btn_top)
    Button mBtnTop;

    @BindView(viewId = R.id.btn_bottom)
    Button mBtnBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AnnotationBinder.bindLayout(this);
        AnnotationBinder.bindView(this);

        mBtnTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "惊喜吧", Toast.LENGTH_SHORT).show();
            }
        });
        mBtnBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Surprise", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
5.运行效果

点击每个按钮都会弹出不同的Toast,下图为点击按钮时效果图。

点击顶部按钮 点击底部按钮

总结

ButterKnife和Dagger2都用到了注解,在应用开发中使用起来简直不要太爽,不过他们的生命周期都是CLASS,不会在代码运行时执行从而不会影响效率。

本篇文章只是一个简单的入门,更多更好玩的东西还等着我们去探索,GO GO GO!!!

相关文章

网友评论

    本文标题:注解入门

    本文链接:https://www.haomeiwen.com/subject/gjfjectx.html