Android进阶之注解解析和自定义注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011311586/article/details/79538900

一:元注解

元注解的作用就是负责注解其他注解

1.@Target

说明:
用来指明注解所修饰的目标,包括packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)

取值:

作用 英文描述
CONSTRUCTOR 用于描述构造器
FIELD 用于描述域 (类的成员变量) Field declaration.
LOCAL_VARIABLE 用于描述局部变量 Local variable declaration.
METHOD 用于描述方法 Method declaration.
PACKAGE 用于描述包 Package declaration.
PARAMETER 用于描述参数 Parameter declaration.
TYPE 用于描述类、接口(包括注解类型) 或enum声明 Class, interface or enum declaration.
CONSTRUCTOR 构造器描述 Constructor declaration.
ANNOTATION_TYPE 注解类型描述 Annotation type declaration.

对应代码:

public enum ElementType {
    /**
     * Class, interface or enum declaration.
     */
    TYPE,
    /**
     * Field declaration.
     */
    FIELD,
    /**
     * Method declaration.
     */
    METHOD,
    /**
     * Parameter declaration.
     */
    PARAMETER,
    /**
     * Constructor declaration.
     */
    CONSTRUCTOR,
    /**
     * Local variable declaration.
     */
    LOCAL_VARIABLE,
    /**
     * Annotation type declaration.
     */
    ANNOTATION_TYPE,
    /**
     * Package declaration.
     */
    PACKAGE
}

举例一:

Target(ElementType.TYPE)
public @interface AnnotationTest1 {
    public String tableName() default "className";
}

小结:
说明这个注解被用来注解
- 类
- 接口(包括注解类型的接口)
- enum

举例二:

@Target(ElementType.FIELD)
public @interface AnnotationTest2 {
}

小结:
说明这个注解被用来注解
- 类的成员变量

2.@Retention

说明:
该注解定义了该Annotation的生命周期某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取。

取值:

作用 英文描述
SOURCE 在源文件中有效(即源文件保留) Annotation is only available in the source code.
CLASS 在class文件&源文件中有效(即class保留) Annotation is available in the source code and in the class file, but nott runtime. This is the default policy.
RUNTIME 在运行时&源文件&class文件有效(即运行时保留) Annotation is available in the source code, the class file and is available at runtime.

对应代码:

public enum RetentionPolicy {
    /**
     * Annotation is only available in the source code.
     */
    SOURCE,
    /**
     * Annotation is available in the source code and in the class file, but not
     * at runtime. This is the default policy.
     */
    CLASS,
    /**
     * Annotation is available in the source code, the class file and is
     * available at runtime.
     */
    RUNTIME
}

举例一:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    public String name() default "fieldName";
    public String setFuncName() default "setField";
    public String getFuncName() default "getField"; 
    public boolean defaultDBValue() default false;
}

小结:
1. 这个注解被用来描述类的成员变量
2. 并且注解一直保留到运行时

3.@Documented

说明:
@Documented的作用是在生成javadoc文档的时候将该Annotation也写入到文档中。

举例一:

@Target(ElementType.METHOD)
@Documented  
public @interface DocumentTest {   
    String hello();   
} 

使用:

public class DocumentClass {   
    /**  
     * this is method of doSomething  
     */  
    @DocumentTest(hello = "yahaitt")   
    public void doSomething() {   
        System.out.println("do something");   
    }   
} 

结果:

@DocumentTest(hello="yahaitt")
public void doSomething()
this is method of doSomething  

4.@Inherited

说明:用在注解的继承,我们自定义注解(Annotation)时,把自定义的注解标注在父类上,但是它不会被子类所继承,我们可以在定义注解时给我们自定义的注解标注一个@Inherited注解来实现注解继承。

举例一:

@Retention(RetentionPolicy.RUNTIME)  
@Inherited  
public @interface InheritedTest {  
    String value();  
} 
@InheritedTest("Jadyer")  
public class Parent {  
    @InheritedTest("JavaEE")  
    public void doSomething() {  
        System.out.println("Parent do something");  
    }  
}
public class Child extends Parent {  

}

测试:

public class Test {  
    public static void main(String[] args) throws SecurityException, NoSuchMethodException {  
        classTest();  
        methodTest();  
    }  

    /** 
     * 通过反射方式测试子类是否会继承父类中定义在类上面的注解 
     */  
    public static void classTest(){  
        Class<Child> c = Child.class; //获取Child的Class对象
        if (c.isAnnotationPresent(InheritedTest.class)) { //判断InheritedTest类是不是Child的父注解类
            InheritedTest inheritedTest = c.getAnnotation(InheritedTest.class);  
            String value = inheritedTest.value();  
            System.out.println(value);  
        }  
    }  

    /** 
     * 通过反射方式测试子类是否会继承父类中定义在方法上面的注解 
     */  
    public static void methodTest() throws SecurityException, NoSuchMethodException{  
        Class<Child> c = Child.class;  
        Method method = c.getMethod("doSomething", new Class[]{});  

        if (method.isAnnotationPresent(InheritedTest.class)) {  
            InheritedTest inheritedTest = method.getAnnotation(InheritedTest.class);  
            String value = inheritedTest.value();  
            System.out.println(value);  
        }  
    }  
}

结果:
- 如果父类的注解是定义在类上面,那么子类是可以继承过来的
- 如果父类的注解定义在方法上面,那么子类仍然可以继承过来
- ++如果子类重写了父类中定义了注解的方法,那么子类将无法继承该方法的注解++

二:Java内建注解

Java提供了三种内建注解

  • @Override——当我们想要复写父类中的方法时,我们需要使用该注解去告知编译器我们想要复写这个方法。这样一来当父类中的方法移除或者发生更改时编译器将提示错误信息。
  • @Deprecated——当我们希望编译器知道某一方法不建议使用时,我们应该使用这个注解。Java在javadoc 中推荐使用该注解,我们应该提供为什么该方法不推荐使用以及替代的方法。
  • @SuppressWarnings——这个仅仅是告诉编译器忽略特定的警告信息,例如在泛型中使用原生数据类型。它的保留策略是SOURCE并且被编译器丢弃。

三:自定义注解

使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。

格式:

public @interface 注解名 {
    定义体
} 

注解参数支持的数据类型
- 所有基本数据类型(int,float,boolean,byte,double,char,long,short)
- String类型
- Class类型
- enum类型
- Annotation类型
- 以上所有类型的数组

参数的设定

  • 只能用public和default修饰
  • 参数成员只能用上面说明的数据类型
  • 如果只有一个参数成员,最好把参数名称设为”value”,后加小括号 (比如:public String[] value();)
  • 可以在使用default为每个参数设置一个默认值。注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定,非基本类型的注解元素的值不可为null。因此, 使用空字符串或0作为默认值是一种常用的做法。(String date() default “”;)

举例一:

@Target(ElementType.FIELD)//用于描述类的字段
@Retention(RetentionPolicy.RUNTIME)//保留到运行时
@Documented//打印文档时显示
public @interface FruitName {
    String value() default "";//默认值是""
}

举例二:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    public enum Color{ BULE,RED,GREEN};//声明颜色枚举
    Color fruitColor() default Color.GREEN;
}

举例三:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitProvider {
     public int id() default -1;

     public String name() default "";

     public String address() default "";
}

使用:

public class Apple {
    @FruitName("Apple")
    private String appleName;
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
}

四:注解的处理

Java在java.lang.reflect 包下新增了AnnotatedElement接口,该接口主要有如下几个实现类:
这里写图片描述

  • Class:类定义
  • Constructor:构造器定义
  • Field:累的成员变量定义
  • Method:类的方法定义
  • Package:类的包定义

所以这些我们经常用的反射手段所用到的类,都实现了AnnotatedElement接口,既然实现了此接口,那么一定有对应的实现方法供我们调用。

//如果存在这样的注解,则返回该元素的指定类型的注解,否则为空。
<T extends Annotation> T getAnnotation(Class<T> annotationClass)
//返回该程序元素上存在的所有注解。
Annotation[] getAnnotations()
//判断该程序元素上是否包含指定类型的注解,存在则返回true,否则返回false.
boolean is AnnotationPresent(Class<?extends Annotation> annotationClass)
//返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。
Annotation[] getDeclaredAnnotations()

可以看到通过反射使用的类,都可以通过指定接口得到在上面注册的注解。所以我们只需要反射得到Class、Method和Constructor,因为AnnotatedElement是Class、Method和Constructor的父接口,它们都实现了AnnotatedElement,所以,在Class、Method和Constructor中就可以使用AnnotatedElement中声明的方法来得到注解和注解内容。

注解实战

++如果没有基础的同学必须先看我前面的java动态代理模式和java注解基础和java反射总结这几篇文章++
自定义注解之动态代理
自定义注解之反射

分析

注解起到一个规范作用&获取值得作用,那么值拿到之后就需要操作值,怎么操作呢?当然通过反射,所以接下来就看如何搞。我们从最熟悉的调用开始展开。

特殊说明
其中Class,Constructor,Field,Method,Package都实现了AnnotatedElement接口
该接口有如下几个方法为核心
//如果存在这样的注解,则返回该元素的指定类型的注解,否则为空。
<T extends Annotation> T getAnnotation(Class<T> annotationClass)
//返回该程序元素上存在的所有注解。
Annotation[] getAnnotations()
//判断该程序元素上是否包含指定类型的注解,存在则返回true,否则返回false.
boolean is AnnotationPresent(Class<?extends Annotation> annotationClass)
//返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。
Annotation[] getDeclaredAnnotations()

实战

自定义注解的话我们需要用项目说话,话不多说

@ContentView(R.layout.activity_main)//布局注解
public class MainActivity extends AppCompatActivity {

    @ViewInject(R.id.btn)//控件注解
    private Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Injector.inject(this);//注册注解
        btn.setText("改变按钮文本");
    }

    @OnClick({R.id.btn})//事件注解
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                Toast.makeText(this, "Button OnClick", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

ContentView

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContentView {
    int value();
}

EventBase

/**
 * 事件注解的基本。如果你需要自行扩展各种事件,如点击事件、选项改变事件等,在该注解上加上此注解。
 */
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EventBase {
    String listenerSetter();
    Class<?> listenerType();
    String callbackMethod();
}

OnClick

/**
 * 点击事件注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@EventBase(listenerSetter = "setOnClickListener", listenerType = View.OnClickListener.class , callbackMethod = "onClick")
public @interface OnClick {
    int[] value();
}

注册器

/**
 * 注射器
 */
public class Injector {

    public static void inject(Activity activity) {
        try {
            injectContentView(activity);
            injectViewInject(activity);
            injectEvents(activity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void injectContentView(Activity activity) {
        Class a = activity.getClass();
        if (!a.isAnnotationPresent(ContentView.class)) return;//判断ContentView注解是不是在该类上面
        ContentView contentView = (ContentView) a.getAnnotation(ContentView.class);
        int layoutId = contentView.value();//得到注解的值
        try {
            Method method = a.getMethod("setContentView", int.class);//得到setContentView方法
            method.setAccessible(true);//设置任意权限可用
            method.invoke(activity, layoutId);//执行
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void injectViewInject(Activity activity) {
        Class a = activity.getClass();
        Field[] fields = a.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(ViewInject.class)) {
                ViewInject viewInject = field.getAnnotation(ViewInject.class);
                int viewId = viewInject.value();
                try {
                    Method method = a.getMethod("findViewById", int.class);
                    method.setAccessible(true);
                    Object resView = method.invoke(activity, viewId);//得到控件
                    field.setAccessible(true);
                    field.set(activity, resView);//设置给activity对象的值是findViewById得到的值相当于(Button btn = findViewById(R.id.btn);)
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private static void injectEvents(Activity activity) {
        Class a = activity.getClass();
        Method[] methods = a.getDeclaredMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(OnClick.class)) {
                OnClick onClick = method.getAnnotation(OnClick.class);
                int[] viewIds = onClick.value();//R.id.btn ...
                EventBase eventBase = onClick.annotationType().getAnnotation(EventBase.class);
                String methodName = eventBase.callbackMethod();//onClick
                String listenerSetter = eventBase.listenerSetter();//setOnClickListener
                Class<?> listenerType = eventBase.listenerType();//View.OnClickListener
                DynamicHandler handler = new DynamicHandler(activity);
                Object listener = Proxy.newProxyInstance(listenerType.getClassLoader(),new Class<?>[] { listenerType } /*listenerType.getInterfaces()*/, handler);//代理View.OnClickListener
                handler.addMethod(methodName, method);//将onClick添加到动态代理里面的容器
                for (int viewId : viewIds) {
                    try {
                        Method findViewByIdMethod = a.getMethod("findViewById", int.class);
                        findViewByIdMethod.setAccessible(true);
                        View view = (View) findViewByIdMethod.invoke(activity, viewId);//得到Button这个View
                        Method setEventListenerMethod = view.getClass().getMethod(listenerSetter, listenerType);//btn.setOnClickListener(View.OnClickListener listener);
                        setEventListenerMethod.setAccessible(true);
                        setEventListenerMethod.invoke(view, listener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

其他相关文章:
自定义注解之动态代理
自定义注解之反射

欢迎关注我们的公众号:码老板,进行更多交流
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u011311586/article/details/79538900