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<Property>{

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

    public static final HashMap<Class,String> propertyTypeMap;

    static {
        propertyTypeMap = new HashMap<Class,String>();
        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<Property> 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<Property> properties(Class clazz){
        if(this.properties == null){
            List<Property> properties = new ArrayList<Property>();
            Field[] fields = clazz.getDeclaredFields();
            for(int i=0,len=fields.length;i<len;i++){
                Field f = fields[i];
                if(f.isAnnotationPresent(Column.class)){
                    Column column = f.getAnnotation(Column.class);
                    Property property = new Property(column.ordinal(),column.type(),column.fieldName(),column.isPrimaryKey(),column.columnName());
                    properties.add(property);
                }
            }
            Collections.sort(properties);
            this.properties =  properties;
        }
        return properties;
    }
}

表的管理輔助類

public class TableManager {

    private static TableManager instance;

    private HashMap<Class,TableConfig> 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、相關代碼:

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)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,321評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,559評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,442評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,835評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,581評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,922評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,931評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,096評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,639評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,374評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,591評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,104評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,789評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,196評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,524評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,322評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,554評論 2 379

推薦閱讀更多精彩內容