android/java 注解

1、在自定义注解之前,需要先理解自定义注解中使用的其他4种注解含义,参考资料。

@Retention
annotation specifies how the marked annotation is stored(用于指定注解存在周期):

SOURCE– The marked annotation is retained only in the source level and is ignored by the compiler.只在源码级别中有效,在编译时无效

CLASS– The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).编译时都还有效,但是会被JVM忽略-->运行时肯定就有问题了,找不到了。

RUNTIME– The marked annotation is retained by the JVM so it can be used by the runtime environment.运行时都有效。

@Documented
annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

@Target
annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.(用于指定这个注解使用的范围)
A target annotation specifies one of the following element types as its value:
ElementType.ANNOTATION_TYPE
can be applied to an annotation type.
ElementType.CONSTRUCTOR
can be applied to a constructor.
ElementType.FIELD
can be applied to a field or property.
ElementType.LOCAL_VARIABLE
can be applied to a local variable.
ElementType.METHOD
can be applied to a method-level annotation.
ElementType.PACKAGE
can be applied to a package declaration.
ElementType.PARAMETER
can be applied to the parameters of a method.
ElementType.TYPE
can be applied to any element of a class.

@Inherited
annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

@Repeatable
annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.

2、自定义一个注解
2.1运行时注解:反射,性能方面稍微较差。

这种注解方式核心是反射,通过反射来获取希望得到的信息。这里以一个简单的demo来描述一下操作步骤:注解方式生成一条建表语句
创建一个Annotation的类,用来标记是要存储的对象

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();// 表名
}

** 创建一个Annotation的类,用来标记某个字段 **

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {

    int ordinal() default 0;

    Class type() default String.class;

    String fieldName() ;

    boolean isPrimaryKey() default false;

    String columnName() default "";

}

**再创建一个普通java类,用来存储字段相关信息 **

public class Property implements Comparable{

    private final int ordinal;
    private final Class type;
    private final String name;
    private final boolean primaryKey;
    private final String columnName;

    public static final HashMap propertyTypeMap;

    static {
        propertyTypeMap = new HashMap();
        propertyTypeMap.put(Long.class,"INTEGER");
        propertyTypeMap.put(Integer.class,"INTEGER");
        propertyTypeMap.put(String.class,"TEXT");
    }

    /**
     * @param ordinal 该字段在表中的索引
     * @param type 该字段属于那种类型,String/Long/Date/Boolean/....
     * @param name 该字段在bean中对应的属性名
     * @param primaryKey 是否为主键
     * @param columnName 在表中的字段名
     */
    public Property(int ordinal, Class type, String name, boolean primaryKey, String columnName) {
        this.ordinal = ordinal;
        this.type = type;
        this.name = name;
        this.primaryKey = primaryKey;
        this.columnName = columnName;
    }

    public int getOrdinal() {
        return ordinal;
    }

    public Class getType() {
        return type;
    }

    public String getName() {
        return name;
    }

    public boolean isPrimaryKey() {
        return primaryKey;
    }

    public String getColumnName() {
        return columnName;
    }

    @Override
    public int compareTo(Property another) {

        if(another.getOrdinal() == ordinal){
            throw new IllegalArgumentException("Property Ordinal Cannot be the same !");
        }

        if(ordinal > another.getOrdinal()){
            return 1;
        }else if(ordinal < another.getOrdinal()){
            return -1;
        }else{
            return 0;
        }
    }
}

** 操作对象 **

@Table("TableBean")
public class TableBean {

    @Column(ordinal = 0,type = Long.class,fieldName = "id",isPrimaryKey = true,columnName = "_id")
    private long id;

    @Column(ordinal = 1,type = String.class,fieldName = "name",isPrimaryKey = false,columnName = "NAME")
    private String name;

    @Column(ordinal = 2,type = Integer.class,fieldName = "age",isPrimaryKey = false,columnName = "AGE")
    private int age;

    public TableBean(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

** 创建SQL语句 **

public class TableConfig {

    private String tableName;

    private List properties;

    public TableConfig(Class clazz){
        tableName(clazz);
        properties(clazz);
    }

    /**
     * 主键问题,建表字段优先顺序问题
     */
    public void create(){
        if(!TextUtils.isEmpty(tableName) && properties.size() > 0){
            StringBuffer sqlBuffer = new StringBuffer("CREATE TABLE ").append(tableName).append("(");
            for(Property property : properties){
                sqlBuffer.append(" ").append(property.getColumnName());
                sqlBuffer.append(" ").append(Property.propertyTypeMap.get(property.getType()));
                if(property.isPrimaryKey()){
                    sqlBuffer.append(" ").append("PRIMARY KEY");
                }
                sqlBuffer.append(",");
            }
            sqlBuffer.deleteCharAt(sqlBuffer.length() - 1);
            sqlBuffer.append(")");
            LogUtils.i(sqlBuffer.toString());
        }
    }

    /**
     * 得到表名
     * @param clazz
     * @return
     */
    public String tableName(Class clazz){
        if(TextUtils.isEmpty(tableName)){
            if(clazz.isAnnotationPresent(Table.class)){
                Table table = (Table) clazz.getAnnotation(Table.class);
                tableName = table.value();
            }
        }
        return tableName;
    }

    /**
     * 得到表中所有字段
     * @param clazz
     * @return
     */
    public List properties(Class clazz){
        if(this.properties == null){
            List properties = new ArrayList();
            Field[] fields = clazz.getDeclaredFields();
            for(int i=0,len=fields.length;i

表的管理辅助类

public class TableManager {

    private static TableManager instance;

    private HashMap tableMap;

    private TableManager(){
        tableMap = new HashMap<>();
    }

    public static TableManager getInstance(){
        if(instance == null){
            synchronized (TableManager.class){
                instance = new TableManager();
            }
        }
        return instance;
    }

    public void createTable(Class clazz){
        TableConfig tableConfig = tableMap.get(clazz);
        if(tableConfig == null){
            tableConfig = new TableConfig(clazz);
            tableMap.put(clazz,tableConfig);
        }
        tableConfig.create();
    }

}

使用

TableManager.getInstance().createTable(TableBean.class);

以上,是一个类似于ORM数据库的最最简单demo,这只是初步,详细框架设计可以看greendao,只不过greendao不是基于annotation来写的。

2.2源码时注解:annotation processor,预编译,性能较好。

基本操作步骤参考这里。在实际操作中注意以下几点即可:
1、annotationprocessor是一个java library,并且包名后缀要和module名一致(这个还要验证,看到eventbus是没有这样限制,但是eventbus是module名和类名一样);
2、必须给这个java library指定resources路径,要不然生成的jar包meta-info信息不对;
3、相关代码:

android/java 注解_第1张图片
QQ截图20160704172800.png

module build.gradle

apply plugin: 'java'

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

tasks.withType(org.gradle.api.tasks.compile.JavaCompile) {
    options.encoding = "UTF-8"
}

sourceSets {
    main {
        java {
            srcDir 'src'
        }
        resources {
            srcDir 'res'
        }
    }
}
sourceCompatibility = org.gradle.api.JavaVersion.VERSION_1_7
targetCompatibility = org.gradle.api.JavaVersion.VERSION_1_7

app build.gradle添加相关配置

android {
    // ......

    compileOptions{
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    lintOptions{    abortOnError false}
    // ......
}
task processorTask(type: org.gradle.api.tasks.Copy) {
    //commandLine 'copy', '../rooboannotationprocessor/build/libs/rooboannotationprocessor.jar', 'libs/'
    from "../rooboannotationprocessor/build/libs/rooboannotationprocessor.jar"
    into "libs/"
}

processorTask.dependsOn(':rooboannotationprocessor:build')
preBuild.dependsOn(processorTask)

你可能感兴趣的:(android/java 注解)