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();
}
java
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 "";
}
sql
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;
}
.net
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;
}
}
get