Android中的自定義註解(反射實現-運行時註解)

預備知識:
Java註解基礎
Java反射原理
Java動態代理

一、佈局文件的註解
我們在Android開發的時候,總是會寫到setContentView方法,爲了避免每次都寫重複的代碼,我們需要使用註解來代替我們做這個事情,只需要在類Activity上聲明一個ContentView註解和對應的佈局文件就可以了。

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.injectContentView(this);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

從上面可以看到,上面代碼在MainActivity上面使用到了ContentView註解,下面我們來看看ContentView註解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContentView {
    int value();
}
  • 1
  • 2
  • 3
  • 4
  • 5

這個註解很簡單,它有一個int的value,用來存放佈局文件的id,另外它註解的對象爲一個類型,需要說明的是,註解的生命週期會一直到運行時,這個很重要,因爲程序是在運行時進行反射的,我們來看看ViewUtils.injectContentView(this)方法,它進行的就是註解的處理,就是進行反射調用setContentView()方法。

    public static void injectContentView(Activity activity) {
        Class a = activity.getClass();
        if (a.isAnnotationPresent(ContentView.class)) {
            // 得到activity這個類的ContentView註解
            ContentView contentView = (ContentView) a.getAnnotation(ContentView.class);
            // 得到註解的值
            int layoutId = contentView.value();
            // 使用反射調用setContentView
            try {
                Method method = a.getMethod("setContentView", int.class);
                method.setAccessible(true);
                method.invoke(activity, layoutId);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

如果對Java註解比較熟悉的話,上面代碼應該很容易看懂。

二、字段的註解
除了setContentView之外,還有一個也是我們在開發中必須寫的代碼,就是findViewById,同樣,它也屬於簡單但沒有價值的編碼,我們也應該使用註解來代替我們做這個事情,就是對字段進行註解。

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
    @ViewInject(R.id.btn1)
    private Button mButton1;
    @ViewInject(R.id.btn2)
    private Button mButton2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.injectContentView(this);
        ViewUtils.injectViews(this);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

上面我們看到,使用ViewInject對兩個Button進行了註解,這樣我們就是不用寫findViewById方法,看上去很神奇,但其實原理很簡單。我們先來看看ViewInject註解。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewInject {
    int value();
}
  • 1
  • 2
  • 3
  • 4
  • 5

這個註解也很簡單,就不說了,重點就是註解的處理了。

    public static void injectViews(Activity activity) {
        Class a = activity.getClass();
        // 得到activity所有字段
        Field[] fields = a.getDeclaredFields();
        // 得到被ViewInject註解的字段
        for (Field field : fields) {
            if (field.isAnnotationPresent(ViewInject.class)) {
                // 得到字段的ViewInject註解
                ViewInject viewInject = field.getAnnotation(ViewInject.class);
                // 得到註解的值
                int viewId = viewInject.value();
                // 使用反射調用findViewById,併爲字段設置值
                try {
                    Method method = a.getMethod("findViewById", int.class);
                    method.setAccessible(true);
                    Object resView = method.invoke(activity, viewId);
                    field.setAccessible(true);
                    field.set(activity, resView);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

上面的註釋很清楚,使用的也是反射調用findViewById函數。

三、事件的註解
在Android開發中,我們也經常遇到setOnClickListener這樣的事件方法。同樣我們可以使用註解來減少我們的代碼量。

@ContentView(R.layout.activity_main)
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewUtils.injectContentView(this);
        ViewUtils.injectEvents(this);
    }

    @OnClick({R.id.btn1, R.id.btn2})
    public void clickBtnInvoked(View view) {
        switch (view.getId()) {
            case R.id.btn1:
                Toast.makeText(this, "Button1 OnClick", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn2:
                Toast.makeText(this, "Button2 OnClick", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

佈局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="#70DBDB"
    android:orientation="vertical"
    tools:context="statusbartest.hpp.cn.statusbartest.MainActivity">
    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Test1"/>

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Test2"/>
</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

可以看到,上面我們沒有對Button調用setOnClickListener,但是當我們點擊按鈕的時候,就會回調clickBtnInvoked方法,這裏我們使用的就是註解來處理的。下面先來看看OnClick註解。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(listenerType = View.OnClickListener.class, listenerSetter = "setOnClickListener", methodName = "onClick")
public @interface OnClick {
    int[] value();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看到這個註解使用了一個自定義的註解。

@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventBase {
    Class listenerType();
    String listenerSetter();
    String methodName();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

下面來看看註解的處理。

    public static void injectEvents(Activity activity) {
        Class a = activity.getClass();
        // 得到Activity的所有方法
        Method[] methods = a.getDeclaredMethods();
        for (Method method : methods) {
            // 得到被OnClick註解的方法
            if (method.isAnnotationPresent(OnClick.class)) {
                // 得到該方法的OnClick註解
                OnClick onClick = method.getAnnotation(OnClick.class);
                // 得到OnClick註解的值
                int[] viewIds = onClick.value();
                // 得到OnClick註解上的EventBase註解
                EventBase eventBase = onClick.annotationType().getAnnotation(EventBase.class);
                // 得到EventBase註解的值
                String listenerSetter = eventBase.listenerSetter();
                Class<?> listenerType = eventBase.listenerType();
                String methodName = eventBase.methodName();
                // 使用動態代理
                DynamicHandler handler = new DynamicHandler(activity);
                Object listener = Proxy.newProxyInstance(listenerType.getClassLoader(), new Class<?>[] { listenerType }, handler);
                handler.addMethod(methodName, method);
                // 爲每個view設置點擊事件
                for (int viewId : viewIds) {
                    try {
                        Method findViewByIdMethod = a.getMethod("findViewById", int.class);
                        findViewByIdMethod.setAccessible(true);
                        View view  = (View) findViewByIdMethod.invoke(activity, viewId);
                        Method setEventListenerMethod = view.getClass().getMethod(listenerSetter, listenerType);
                        setEventListenerMethod.setAccessible(true);
                        setEventListenerMethod.invoke(view, listener);
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

這個代碼相對上面的要複雜一些,它使用到了動態代理,關於動態代理的基本用法可以看看前面我提到的預備知識。

public class DynamicHandler implements InvocationHandler {
    private final HashMap<String, Method> methodMap = new HashMap<String, Method>(
            1);
    // 因爲傳進來的爲activity,使用弱引用主要是爲了防止內存泄漏
    private WeakReference<Object> handlerRef;
    public DynamicHandler(Object object) {
        this.handlerRef = new WeakReference<Object>(object);
    }

    public void addMethod(String name, Method method) {
        methodMap.put(name, method);
    }
    // 當回到OnClickListener的OnClick方法的時候,它會調用這裏的invoke方法
    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        // 得到activity實例
        Object handler = handlerRef.get();
        if (handler != null) {
            // method對應的就是回調方法OnClick,得到方法名
            String methodName = method.getName();
            // 得到activtiy裏面的clickBtnInvoked方法
            method = methodMap.get(methodName);
            if (method != null) {
                // 回調clickBtnInvoked方法
                return method.invoke(handler, objects);
            }
        }
        return null;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

基本的看註釋就應該差不多了。

http://blog.csdn.net/hp910315/article/details/51199748 —–》出處

發佈了58 篇原創文章 · 獲贊 22 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章