package com.wind.test.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- 文件名称 : DataBaseTable.java
- 作 者 : Ranger
- 创建时间 : 2015-1-12 上午9:27:49
- 文件描述 :注解得到表名
- 修改历史 : 2015-1-12 1.00 初始版本
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataBaseTable {
public String tableName();
}
package com.wind.test.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- 文件名称 : ColumnsName.java
- 作 者 : Ranger
- 创建时间 : 2015-1-12 上午9:25:30
- 文件描述 : 注解字段,得到字段名
- 修改历史 : 2015-1-12 1.00 初始版本
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ColumnsName {
String fieldName() default "";
}
package com.wind.test.annotationTest.model;
import com.wind.test.annotation.ColumnsName;
import com.wind.test.annotation.DataBaseTable;
@DataBaseTable(tableName = "CustomModel")
public class CustomModel{
@ColumnsName(fieldName = "userId")
public String a_mImUserId;
@ColumnsName(fieldName = "UserCustomList")
public byte[] b_mUserCustomList;
@ColumnsName(fieldName = "datatype")
public int c_mType;
}
package com.wind.test.annotationTest;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import com.wind.test.annotation.ColumnsName;
import com.wind.test.annotation.DataBaseTable;
import com.wind.test.annotationTest.model.CustomModel;
public class AnnotationTest {
/**
* 运行注解,拼出sql
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Field[] fields = CustomModel.class.getFields();
DataBaseTable tableModel = (DataBaseTable) CustomModel.class.getAnnotation(DataBaseTable.class);
String tableName = tableModel.tableName();
String sql = "CREATE TABLE IF NOT EXISTS " + tableName + "(";
for (int i = 0; i < fields.length; i++) {
ColumnsName tabFeild = fields[i].getAnnotation(ColumnsName.class);
if(tabFeild != null){
if(i == 0){
sql = sql + tabFeild.fieldName() + " " + getColumnType(fields[i].getType());
}else{
sql =sql + " ," + tabFeild.fieldName() + " " + getColumnType(fields[i].getType());
}
}
}
sql = sql + ");";
System.out.println(sql);
}
/**
* 得到type
* @param type
* @return
*/
public static String getColumnType(Type type) {
String colums = "TEXT";
if (type == Long.class || (type == Long.TYPE)) {
} else if (Integer.class == type || (type == Integer.TYPE)) {
colums = "INTEGER";
} else if (type == String.class) {
} else if (type == byte[].class) {
colums = "BLOB";
}
return colums;
}
}
网友评论