關於android註解的思考和實現方式

來源:互聯網
上載者:User

關於android註解的思考和實現方式

我們平常在開發web項目的時候,經常會使用SSH來構建我們的項目,也有很多程式猿喜歡用註解來減少代碼量。但是各位屌絲程式猿們,大家有沒有想過這個註解是怎麼實現的呢。我們又該如何寫出像註解這麼優雅的代碼呢。除了我們平時在寫代碼的時候看到了新的東西之後始終保持探索的精神。還要有大家拿出極大的熱情刻苦專研和對待代碼一絲不苟的精神。這樣才能使得自己進步,寫出更加優雅的代碼。今天我帶大家來寫一個註解類,初始化android控制項。

廢話少說,先上一段代碼。

package com.example.volley.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//聲明在field@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface ViewInject {int value() default 0;}

首先看這段代碼,相信大家之前沒有寫過的童鞋肯定看的一頭霧水。所以我解釋一些。@interface這是java用來定義一個註解類。

@Target和@Retention這兩個是JDK提供的元註解。請看下面。

@Target(ElementType.TYPE) //介面、類、枚舉、註解
   @Target(ElementType.FIELD) //欄位、枚舉的常量
   @Target(ElementType.METHOD) //方法
   @Target(ElementType.PARAMETER) //方法參數
   @Target(ElementType.CONSTRUCTOR) //建構函式
   @Target(ElementType.LOCAL_VARIABLE)//局部變數
   @Target(ElementType.ANNOTATION_TYPE)//註解
   @Target(ElementType.PACKAGE) ///包
@Retention(RetentionPolicy.RUNTIME) // 註解會在class位元組碼檔案中存在,在運行時可以通過反射擷取到

簡單解釋一下,比如ElementType.TYPE這個表示是一個類註解。比如struts2和springMVC的@controller

這個註解。

RetentionPolicy.RUNTIME表示會在class檔案中運行是通過反射得到。

 

註解類寫好了,下面關鍵的是如何註解解析。

老辦法,先上代碼。

package com.example.volley.annotation;import java.lang.reflect.Field;import java.lang.reflect.Method;import android.app.Activity;public class ViewUtils { public static ViewUtils viewUtils; public Activity ctx; public ViewUtils(Activity ctx) {  this.ctx = ctx;  autoInjectAllField(); }  public static ViewUtils inject(Activity ctx){  if (viewUtils!=null) {   return viewUtils;  }else{   viewUtils = new ViewUtils(ctx);   return viewUtils;  } }  private void autoInjectAllField() {  try {   Class clazz = ctx.getClass();         Field[] fields = clazz.getDeclaredFields();   for (Field field : fields) {    if (field.isAnnotationPresent(ViewInject.class)) {     ViewInject inject = field.getAnnotation(ViewInject.class);     int id = inject.value();     if(id > 0){      field.setAccessible(true);      field.set(ctx, ctx.findViewById(id));     }    }   }  } catch (Exception e) {   e.printStackTrace();  }  }}


通過ctx.getclass()得到實體類。然後得到這個類中所有的註解跟ViewInject註解類匹配。如果匹配成功,則set(ctx,ctx.findById());

寫到這裡,大家想必都明白了。今天先這樣,見。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.