注解入門(mén)

一個(gè)人有無(wú)成就,取決于他青年時(shí)期是不是有志氣。 — 謝覺(jué)哉

寫(xiě)在前面

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

首先需要認(rèn)識(shí)以下注解:

  • @Documented:是否要將注解信息添加到Java文檔中。
  • @Retention:注解的生命周期。
  • @Target:注解的作用目標(biāo)。
  • @Inherited:定義注解與子類(lèi)的關(guān)系,在繼承情況下默認(rèn)是不會(huì)繼承注解的,除非是使用@Inherited聲明的注解,但只對(duì)類(lèi)有效,對(duì)方法/屬性無(wú)效。

生命周期

@Retention注解是用來(lái)聲明注解的生命周期的,那么就看看它都有哪些生命周期可用。

/**
 * 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注解可用的生命周期,它是一個(gè)枚舉類(lèi),可用的生命周期有三種:

  • SOURCE:在編譯時(shí)丟棄,也就是說(shuō)在編譯結(jié)束后這個(gè)注解將沒(méi)有任何意義,不會(huì)寫(xiě)入字節(jié)碼。
  • CLASS:在類(lèi)加載時(shí)丟棄,也就是說(shuō)在類(lèi)加載結(jié)束后這個(gè)注解的信息將被寫(xiě)入字節(jié)碼,是默認(rèn)的生命周期。
  • RUNTIME:永遠(yuǎn)不會(huì)被丟棄,始終存在于運(yùn)行時(shí),可以通過(guò)反射機(jī)制讀取注解信息。

作用目標(biāo)

@Target注解是用來(lái)聲明注解的作用目標(biāo)的,那么就看看它都可以聲明在哪些類(lèi)型上。

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注解的可作用目標(biāo),它也是一個(gè)枚舉類(lèi),可用的作用目標(biāo)目前有十種:

  • TYPE:用于描述類(lèi)、接口(包括注解類(lèi)型) 或enum聲明 Class。
  • FIELD:用于描述域(屬性)。
  • METHOD:用于描述方法。
  • PARAMETER:用于描述參數(shù)。
  • CONSTRUCTOR:用于描述構(gòu)造器。
  • LOCAL_VARIABLE:用于描述局部變量。
  • ANNOTATION_TYPE:用于描述注解類(lèi)。
  • PACKAGE:用于描述包。
  • TYPE_PARAMETER:用來(lái)標(biāo)注類(lèi)型參數(shù)。
  • TYPE_USE:能標(biāo)注任何類(lèi)型名稱(chēng)。

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

如何使用

下面通過(guò)一個(gè)例子來(lái)認(rèn)識(shí)注解:

在Android應(yīng)用開(kāi)發(fā)中,難免要在Activity中使用setContentView和findViewById,一旦布局中的View很多,就要寫(xiě)好多好多的findViewById,導(dǎo)致代碼很多,閱讀性差。注解的出現(xiàn)幫助我們解決了這個(gè)問(wèn)題,可以通過(guò)自定義注解減少findViewById代碼,提升閱讀性。

1.自定義注解

首先定義兩個(gè)自定義注解,一個(gè)的使用范圍是TYPE,作于在類(lèi)上用于setContentView;另一個(gè)的使用范圍是FIELD,作用在屬性上用于findViewById;這兩個(gè)注解的生命周期都是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.讀取注解信息

現(xiàn)在創(chuàng)建一個(gè)輔助類(lèi),只需要傳入Activity即可,通過(guò)反射機(jī)制讀取注解信息,將讀取到不同的注解信息進(jìn)行setContentView和findViewById。

public class AnnotationBinder {

    public static void bind(Activity activity) {
        if (activity == null) {
            throw new NullPointerException("Activity can't be null");
        }

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

        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.創(chuàng)建布局

寫(xiě)一個(gè)僅有兩個(gè)按鈕的布局。

<?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="點(diǎn)擊我 !??!"
        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="點(diǎn)擊我 ?。?!"
        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.創(chuàng)建Activity

下面要在Activity中使用自定義注解了,只需在需要的地方聲明注解傳入相應(yīng)的值即可,調(diào)用 AnnotationBinder.bind(this)就會(huì)自動(dòng)setContentView和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.bind(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.運(yùn)行效果

點(diǎn)擊每個(gè)按鈕都會(huì)彈出不同的Toast,下圖為點(diǎn)擊按鈕時(shí)效果圖。

點(diǎn)擊頂部按鈕
點(diǎn)擊底部按鈕

總結(jié)

ButterKnife和Dagger2都用到了注解,在應(yīng)用開(kāi)發(fā)中使用起來(lái)簡(jiǎn)直不要太爽,不過(guò)他們的生命周期都是CLASS,在類(lèi)加載階段丟棄,會(huì)寫(xiě)入到class文件,不會(huì)加載到JVM中,不會(huì)在代碼運(yùn)行時(shí)通過(guò)反射機(jī)制解析注解信息而影響效率。

本篇文章只是入門(mén),讀取注解信息的例子采用了運(yùn)行時(shí)注解,使用編譯時(shí)注解也可以實(shí)現(xiàn),那么問(wèn)題來(lái)了,編譯時(shí)注解是什么?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容