學習Butterknife的一點心得(系列)一

來源:互聯網
上載者:User

標籤:

我們實現一個完整的一個例子,那麼基本瞭解了其運行機制。

1  建立一個處理註解的項目

    

依次為一個註解,一個註解處理器,一個註解路徑設定檔(供編譯器識別)。

註解Seriable代碼:

@Target({ ElementType.FIELD, ElementType.TYPE })  @Retention(RetentionPolicy.CLASS) public @interface Seriable {}

@Retention標明生命週期,

RetentionPolicy.CLASS //表示註解是在編譯期處理

這個設定檔的內容是BeanProcessor.java的完整路徑:com.zhy.annotationprocess.processor.BeanProcessor.

這個BeanProcessor.java的代碼為:

@SupportedSourceVersion(SourceVersion.RELEASE_6)public class BeanProcessor extends AbstractProcessor { // 元素操作的輔助類Elements elementUtils;ProcessingEnvironment  processingEnv;@Overridepublic synchronized void init(ProcessingEnvironment processingEnv) {super.init(processingEnv);// 元素操作的輔助類elementUtils = processingEnv.getElementUtils();this.processingEnv = processingEnv;}@Overridepublic Set<String> getSupportedAnnotationTypes() {Set<String> typeSet = new LinkedHashSet<String>();typeSet.add(Seriable.class.getCanonicalName());return typeSet;}@SuppressWarnings("resource")@Overridepublic boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) {processingEnv.getMessager().printMessage(Kind.ERROR, "12346789");// 獲得被該註解聲明的元素Set<? extends Element> elememts = roundEnv.getElementsAnnotatedWith(Seriable.class);TypeElement classElement = null;// 聲明類元素List<VariableElement> fields = null;// 聲明一個存放成員變數的列表// 存放二者Map<String, List<VariableElement>> maps = new HashMap<String, List<VariableElement>>();try {// 遍曆File file = new File("f:/test.txt");FileWriter fWriter = null;fWriter = new FileWriter(file,true);FileOutputStream outputStream = new FileOutputStream(file,true);outputStream.write((" ======elememts size : " +elememts.size()+ "\n").getBytes());int i = 1;for (Element ele : elememts) {//processingEnv.getMessager().printMessage(Kind.ERROR, "12346789",ele);outputStream.write((" ======start\n").getBytes());outputStream.write((" element name:" + ele.getSimpleName() + " index:" + i + "\n").getBytes());outputStream.write((" element enclose_name:"+ele.getEnclosingElement().getSimpleName()+"\n").getBytes());outputStream.write(( "element kind:" + ele.getKind().name() + "\n").getBytes());outputStream.write(( " element type:" + ele.asType().getKind().name() + "\n").getBytes());outputStream.write(("========end\n").getBytes());i++;}outputStream.flush();outputStream.close();} catch (IOException e) {e.printStackTrace();}return true;}}

然後將其打成一個jar。


2  建立一個測試簡單註解架構的項目

  

percent_1.jar就是剛才打的jar包


Article.java和User.java的代碼分別為:

@Seriable  public class Article  {       private String title ;              private String content ;        }   public class User   {      @Seriable     int username123;                @Seriable       String password123;        private String three;       private String four;   }

對AnntotaionTest1項目配置,使編譯器能識別jar中的註解處理器BeanProcessor。


配置完之後回頭看BeanProcessor,編譯器識別它之後,會調用它的process(...)入口,根據代碼會在F盤建立一個test.txt檔案,裡面列印了被註解的元素的資訊。現在我們來看一下這個檔案的內容:

 ======elememts size : 3

 ======start

 element name:username123 index:1

 element enclose_name:User

element kind:FIELD

 element type:INT

========end

 ======start

 element name:Article index:2

 element enclose_name:com

element kind:CLASS

 element type:DECLARED

========end

 ======start

 element name:password123 index:3

 element enclose_name:User

element kind:FIELD

 element type:DECLARED

========end

 ======elememts size : 0

果然列印出了3條註解元素的資訊,這和我們在User和Article註解的元素一一對應。

這裡解釋一下:element name的值意思為註解元素的名稱,element enclose_name:是封裝這個元素的實體名稱,element kind的值被註解元素的角色,欄位或者類等其他,element type:的值表示被註解元素的類型,username123被定義成int,它的type就為INT,password123被定義成String,它的type就為DECLARED。至此簡單的編譯註解完成測試。在寫註解處理器的時候有一點要注意,就是必須實現getSupportedAnnotationTypes()方法


學習Butterknife的一點心得(系列)一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.