Java 使用annotation註解 - (一)

      在使用Java快4年的時間了 是時候應該留下點東西了。今天又在寫實體類 pojo 感受一直在寫 一直在使用mybatis的註解 spring的註解 今天就看看源碼裏面是怎麼定義的。 能夠關注個人新浪微博 : 瘋狂的楊中仁java

首先要研究註解 我只記得annotation 以及基本的用法 public @interface ****{}mysql

在網上找了一些資料 看了再上面定義@Documented說明是這個是註解 而後在@Documented這個註解下面 咱們看到了spring

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}

看基本的意思就是sql

@Retention(RetentionPolicy.RUNTIME) 就是在上面時候運行 數據庫

@Target(ElementType.ANNOTATION_TYPE) 這個註解的意思就是 在上面類型上面運行。json

那麼咱們就使用這個原註解上面的3個註解 模仿hibernate寫一個 mybatis

定義一個Table註解 本身的額測試

首先定義一個數據庫類型的枚舉
this

public enum DBEnum {

	// 定義數據庫枚舉 2015年5月17日22:41:47
	MYSQL, ORACLE, MSSQL, DB2, SYBASE

}

接着定義一個Table註解.net

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Table {

	public String value() default ""; // 使用表的名稱
	
	// 定義數據庫枚舉
	public DBEnum type() default DBEnum.MSSQL; // 默認使用mysql數據庫
}

在下面定義Column註解

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

	// 使用數據庫的列的名稱
	public String value() default ""; // 默認使用‘’
	
}

一張表下面必需要有的還有id 在作保存的時候 必須的 呵呵 下面增長一個ID註解

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

	// 在列上面使用id註解 說明這個列是id列 在作保存的時候 使用本身增長的策略 2015年5月17日22:44:43
	public boolean unique() default false; // 使用惟一的約束 2015年5月17日22:46:43

}

註解定義好了 那麼下面 咱們是要寫一個實體類 也就是pojo

public class User {

	@ID
	@Column
	private int userid;
	
	@Column
	private String username;
	
	@Column
	private String password;
	
	@Column
	private String createtime;
	
	@Column
	private String updatetime;
	
	@Column
	private String telephone;
	
	@Column
	private int status;
	
	@Column
	private String nickname;
	
	@Column
	private int integral;

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCreatetime() {
		return createtime;
	}

	public void setCreatetime(String createtime) {
		this.createtime = createtime;
	}

	public String getUpdatetime() {
		return updatetime;
	}

	public void setUpdatetime(String updatetime) {
		this.updatetime = updatetime;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public int getIntegral() {
		return integral;
	}

	public void setIntegral(int integral) {
		this.integral = integral;
	}

}

記得在上面增長上咱們以前定義好的註解 


下面咱們就能夠在下面解析這個註解  直接上代碼吧  有什麼不懂的能夠在下面評論額

public class AplasMain {
	
	
	// 測試方法 2015年5月17日22:32:23
	public static void main(String[] args) throws Exception {
		
		// 定義一個user類型 反射這個類型下面全部的字段
		Map<String, Object> map = new HashMap<String, Object>();
		Class<? extends Object> clazz = User.class;
		
		map.put("className", clazz.getSimpleName());
		map.put("tableName", clazz.getSimpleName());
		
		// 判斷 若是類型使用了Table註解
		if (clazz.isAnnotationPresent(Table.class)) {
			Table table = clazz.getAnnotation(Table.class);
			if (table!=null && !table.value().equals("")) { // 默認值設置的是「」 因此直接判斷是不是""就能夠
				map.put("tableName", table.value());
			}
		}
		
		//拿出這個類型下面全部的字段
		Field[] fields = clazz.getDeclaredFields();
		// 判斷下面的字段
		List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
		for (Field field : fields) {
			Map<String, Object> fieldMap = new HashMap<String, Object>();
			fieldMap.put("property", field.getName());
			fieldMap.put("column", field.getName());
			fieldMap.put("unique", false);
			// 判斷是否使用了column註解
			if (field.isAnnotationPresent(Column.class)) {
				Column column = field.getAnnotation(Column.class);
				if (column!=null && !column.value().equals("")) {
					fieldMap.put("column", column.value());
				}
			}
			// 判斷是否使用id註解
			if (field.isAnnotationPresent(ID.class)) {
				ID id = field.getAnnotation(ID.class);
				if (id!=null && !id.unique()) {
					fieldMap.put("unique", true);
				}
			}
			// 最後把這個放在list下面
			mapList.add(fieldMap);
		}
		
		map.put("list", mapList);
		
		// 打印成json的 看下結果
		System.out.println(JSONArray.fromObject(map));
	}
	
	
}

最後看一下輸出的結果 

[
    {
        "tableName": "User",
        "list": [
            {
                "unique": true,
                "column": "userid",
                "property": "userid"
            },
            {
                "unique": false,
                "column": "username",
                "property": "username"
            },
            {
                "unique": false,
                "column": "password",
                "property": "password"
            },
            {
                "unique": false,
                "column": "createtime",
                "property": "createtime"
            },
            {
                "unique": false,
                "column": "updatetime",
                "property": "updatetime"
            },
            {
                "unique": false,
                "column": "telephone",
                "property": "telephone"
            },
            {
                "unique": false,
                "column": "status",
                "property": "status"
            },
            {
                "unique": false,
                "column": "nickname",
                "property": "nickname"
            },
            {
                "unique": false,
                "column": "integral",
                "property": "integral"
            }
        ],
        "className": "User"
    }
]

是咱們想要的結果 說明解析出來是對的。

下面一篇文章講講解annotation的原理。謝謝關注 

相關文章
相關標籤/搜索