文章目录
  1. 1. 一、define a annotation
  2. 2. 二、use the annotation
  3. 3. 三、parse the annotation

一、define a annotation

1
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME) 
public @interface ViewInject {  
  	int value() default 0 ;  
}

二、use the annotation

1

@ViewInject(R.id.tv_name)
private TextView myTextView;

三、parse the annotation

1
public void parseAnnotation(Class<?>  clazz) {  	//传一个类进来
    	try {  
         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(this, this.findViewById(id));			//给字段设置值  
                 }  
             }  
         }  
     } catch (IllegalAccessException e) {  
         e.printStackTrace();  
    } catch (IllegalArgumentException e) {  
         e.printStackTrace();  
      }  
 }
文章目录
  1. 1. 一、define a annotation
  2. 2. 二、use the annotation
  3. 3. 三、parse the annotation