国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > 综合技术 > android 框架基础之java注解

android 框架基础之java注解

来源:程序员人生   发布时间:2017-02-15 09:16:41 阅读次数:3304次

现在准备研究1些源码或框架,但是1些基础的知识1定要懂,不然没法看,比如设计模式,java基础中的反射,泛型,注解,多线程,线程池,队列等,现在很多框架都是这些知识杂糅而成的,

我们经常使用的java内置3大注解:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

上面onCreate()方法上@Override就是注解,我们点击进去看看,

package java.lang;

import java.lang.annotation.*;

/**
 * Indicates that a method declaration is intended to override a
 * method declaration in a supertype. If a method is annotated with
 * this annotation type compilers are required to generate an error
 * message unless at least one of the following conditions hold:
 *
 * <ul><li>
 * The method does override or implement a method declared in a
 * supertype.
 * </li><li>
 * The method has a signature that is override-equivalent to that of
 * any public method declared in {@linkplain Object}.
 * </li></ul>
 *
 * @author  Peter von der Ah&eacute;
 * @author  Joshua Bloch
 * @jls 9.6.1.4 Override
 * @since 1.5
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

@interface就是表明声明1个注解类,在java.lang包下,发现声明的注解Override上面有2个@Target和@Retention这2个注解,

@Target(ElementType.METHOD) 表示注解类(Override)使用再方法上

@Retention(RetentionPolicy.SOURCE) 表示使用再源码中

@Target说明了Annotation所修饰的对象范围

再点击Target进去看看:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    ElementType[] value();
}
我们发现
@Target(ElementType.ANNOTATION_TYPE)

()这个括号里的是啥东西呢,还是点击进去看看源码:

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     * @hide 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     * @hide 1.8
     */
    TYPE_USE
}
这是JDK1.5后出来的,也就是说1.5之前是没注解的,ElementType 这是1个枚举类,这个枚举类中定义了10个变量,哪这10个变量都是啥意思呢?

 @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) ///包

Target注解类中还有1个声明注解

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    RetentionPolicy value();
}

@Retention

表示注解的作用时段

取值(RetentionPoicy)有: 
1.SOURCE:在源文件中有效(即源文件保存) 
2.CLASS:在class文件中有效(即class保存) 
3.RUNTIME:在运行时有效(即运行时保存)

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

源码中RetentionPolicy 也是1个枚举类,定义了3个变量

java内置3大注解:

1:@Override

定义在java.lang.Override中,此注解只适应于修饰方法,表示1个方法声明打算重写超类(父类)的另外一个方法声明

package com.annotation;
/**
 * Created by admin on 2017/1/10.
 */
public interface Person {
     String getName();
     int getAge();
     void sing();
}
这是我们自己写的1个接口,

package com.annotation;
/**
 * Created by admin on 2017/1/10.
 */
public class Child implements Person {
    @Override
    public String getName() {
        return null;
    }
    @Override
    public int getAge() {
        return 0;
    }
    @Override
    public void sing() {

    }
}
我们发现Child实现了Person接口,getName(),getAge(),sing()方法上都有@Override注解,表明这3个方法都是来自接口Person

2:@Deprecated

定义在java.lang.Deprecated中,此注解可修饰类,方法,属性,表示不建议程序员使用这个方法,属性,类等,表示它已过时,有更好的选择或存在危险,下面我是我平时开发中很常见的过时正告:


3:@SuppressWarnings中,用来拟制编译时正告信息,下面的代码也是很常见的


哪怎样修复呢?有2种,1种是依照提示去补充代码,比如List要添加泛型,表示这个list存储的是甚么类型的数据,还有1种就是使用注解,


这个正告信息就没了,

放在变量前面也行:


在jdk源码中这个注解也到处都是

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p>Compiler vendors should document the warning names they support in
     * conjunction with this annotation type. They are encouraged to cooperate
     * to ensure that the same names work across multiple compilers.
     */
    String[] value();
}

String[] value();我刚开始以为是方法,后来发现理解错了,value是参数名,String[]是参数类型,

如果想要使用这个注解,就必须最少添加1个参数,这些参数值都是定义好的,以下:


比如这么使用:

如果只有1个参数的话可以这么使用

@SuppressWarnings("all")

如果是多个参数的话,这么使用:

@SuppressWarnings(value={"all","unchecked"})


自定义注解:

使用@interface自定义注解时,自动继承了java.lang.annotatin.Annotation

@interface用来声明1个注解

格式:public @interface 注解名

其中每个方法实际上是声明1个配置参数,就和我们上面讲的SuppressWarnings1样,

方法的名称就是参数的名称

返回值类型就是参数的类型(返回值类型只能是基本类型,Class,String,enum)
可以通过default来声明参数的默许值

如果只有1个参数成员,1般参数名为value.


如果1个注解中甚么都没有的话就是1个标记注解,比如:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
没有定义参数和参数类型,

在android studio中定义1个注解类:在这里选择,


package com.annotation;
/**
 * Created by admin on 2017/1/11.
 */
public @interface MyAnnotation {
}
它默许是继承了Annotation,就像你随意定义1个Person,它也是隐士的继承了Object类1样,

1般定义注解都要在这个注解上定义2个元注解,那末甚么是元注解呢?


元注解:

元注解的作用就是负责注解其他的注解,对注解进行描写,java定义了4个标注的meta-annotation类型,他们被用来对其他Annotation类型的说明,分别有以下4个:

@Target:用于描写注解的使用范围(也就是说注解可以被用在甚么地方),

public @interface Target {
    ElementType[] value();
}

它是有参数名和参数类型的,上面已说明了,在这就不描写了

@Retention:表示在甚么级别保存该注释信息,用于描写注解的生命周期


1般都是使用RUNTIME,由于你自定义注解肯定是希望通过反射在运行时读取啊,而前2者通知是在编译时期,如果使用了RUNTIME,那末就包括前2者,由于它生命周期最长,如果定义了前2者反射是读取不到的.

@Documented:Documented 注解表明这个注解应当被 javadoc工具记录. 默许情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中

现在在eclipse中如何演示生成1个文档:

第1步点击项目:选择Export

第2步:


第3步:


第4步:在eclipse下运行生成文档


第5步:在之前选择寄存文档的目录中找到生成的文档:


看到这个相信大家都明白了,jdk中文或英文文档是否是有这个了,然后点击index.html查看


@Inherited:允许子类继承父类的注解

上面把元注解讲完了,现在自定义注解:

package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by admin on 2017/1/11.
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
     String name();
}

解释:


使用:


发现报错了,解决这类办法有2个方法

第1个方法:

设置默许值:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
     String name() default "";
}

第2种方法:

public class Test {
    @MyAnnotation(name="zhou")
    public void test(){

    }
}
这就是自定义注解了,我写的是1个简单的,其实复杂的也就是所谓的参数多点而已,

使用反射读取注解内容

写这个例子就是使用注解和反射知识动态的生成1条sql语句,现在很多框架估计也是这么干的,只是料想,没看过网上那些3方数据库框架的源码,

package com.annotation;
/**
 * Created by admin on 2017/1/11.
 */
@UserAnnotion("table_user")
public class User {
    @AttrsAnnotation(columnName = "id",type ="int",len = 10)
    private int id;
    @AttrsAnnotation(columnName = "name",type ="varchar",len = 10)
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
对类名进行注解跟表名进行xiangguan

package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * Created by admin on 2017/1/11.
 */
@Target(value= {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserAnnotion {
    String value();//与表名对应
}
类中的属性和表字段进行相干联通过注解的方式

package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * 修饰表中属性的注解
 * Created by admin on 2017/1/11.
 */
@Target(value= {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AttrsAnnotation {
    String columnName() default "";
    String  type() default "";
    int len() default 10;
}
终究动态的生成sql语句:

/**
 * 读取User中的数据 动态生成sql语句
 */
public void table(){
    try {
        Class clazz = Class.forName("com.annotation.User");
        if(clazz!=null){
            UserAnnotion userAnnotion = (UserAnnotion) clazz.getAnnotation(UserAnnotion.class);
            String table_name = userAnnotion.value();//获得表名
            Field nameFiled = clazz.getDeclaredField("name");
            Field idFiled = clazz.getDeclaredField("id");
            AttrsAnnotation nameFiledAnnotation = nameFiled.getAnnotation(AttrsAnnotation.class);
            AttrsAnnotation idFiledAnnotation = idFiled.getAnnotation(AttrsAnnotation.class);
            String tabpPre = "CREATE TABLE IF NOT EXISTS ";
            String sql=tabpPre+table_name+"("+"_id INTEGER PRIMARY KEY AUTOINCREMENT"+","+nameFiledAnnotation.columnName()+" "+nameFiledAnnotation.type()+"("+nameFiledAnnotation.len()+")"+","+idFiledAnnotation.columnName()+" "+idFiledAnnotation.type()+")";
            Log.e(TAG,"SQL="+sql);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}
结果:

CREATE TABLE IF NOT EXISTS table_user(_id INTEGER PRIMARY KEY AUTOINCREMENT,name varchar(10),id int)

如图调用:


如果知道这些理论,以后看3方数据库框架应当轻松很多的,就写到这吧


生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生