您的位置:首页 > 其它

元注解 摘要

2018-01-15 19:18 148 查看
/**
*   @Target  {
*       作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
  取值(ElementType)有:
    1.CONSTRUCTOR:用于描述构造器
    2.FIELD:用于描述域
    3.LOCAL_VARIABLE:用于描述局部变量
    4.METHOD:用于描述方法
    5.PACKAGE:用于描述包
    6.PARAMETER:用于描述参数
    7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
*   }
*
*   @Retention
*作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
  取值(RetentionPoicy)有:
    1.SOURCE:在源文件中有效(即源文件保留)
    2.CLASS:在class文件中有效(即class保留)  类似@ovveride
    3.RUNTIME:在运行时有效(即运行时保留)
*
*@Documented:
  用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
*
* @Inherited:
*  元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
  注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。

@interface
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。
  定义注解格式:
  public @interface 注解名 {定义体}
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldView {
int value();
}
public class ViewFind {
public static void bind(Activity activity) {
Class<? extends Activity> aClass = activity.getClass();

Field[] declaredFields = aClass.getDeclaredFields();

if (declaredFields != null && declaredFields.length > 0) {
for (Field field : declaredFields) {
Class<?> type = field.getType();
if (
//是否是静态的
Modifier.isStatic(field.getModifiers())
//是否是final的
|| Modifier.isFinal(field.getModifiers())
//是否是基本类型
|| type.isPrimitive()
//是否是数组
|| type.isArray()) {
continue;
}

//获取注解
FieldView annotation = field.getAnnotation(FieldView.class);
if (annotation != null) {
View view = activity.findViewById(annotation.value());
if (view != null) {
field.setAccessible(true);
try {
field.set(activity, view);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}

}
}
}
}使用:
@FieldView(R.id.tv_text)
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewFind.bind(this);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  元注解