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、相關代碼:
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)