1. 程式人生 > 實用技巧 >java - 反射操作註解

java - 反射操作註解

反射操作註解

模擬ORM( 物件關係對映 ), 利用註解和反射完成類和表結構的對映關係

類名 表名
屬性 表字段
一個類物件 表中的一條記錄

完整示例程式碼:

package com.hz;

import com.sun.deploy.util.StringUtils;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.util.Arrays;


@TableName("user")  // 資料庫中有一張名為User的表
public class User {
    @DBField(name = "name", type = "NVARCHAR2", len = 50, nullable = false)//庫中name欄位
    private String userName;  

    @DBField(name = "pwd", type = "NVARCHAR2", len = 100, nullable = false)//庫中pwd欄位
    private String passWord;
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface DBField{
    String name();
    String type();
    int len();
    boolean nullable();
}

class MyOrm{
    public static void main(String[] args) throws Exception {
        // sql有了就可以通過 jdbc來獲取資料了
        String sql = new MyOrm().getSelectSql();
        System.out.println(sql);
    }

    private String getSelectSql() throws ClassNotFoundException {
        Class clz = Class.forName("com.hz.User");

//        // 獲取所有註解
//        Annotation[] annotations = clz.getAnnotations();
//        for (Annotation annotation : annotations) {
//            System.out.println(annotation);
//        }

        // 獲取表名的註解
        TableName annTable = (TableName) clz.getAnnotation(TableName.class);
//        System.out.println(annTable.value());

        // 獲取欄位的註解
        Field[] declaredFields = clz.getDeclaredFields();
        String[] fields = new String[declaredFields.length];
        for (int i = 0; i < declaredFields.length; i++) {
            Field declaredField = declaredFields[i];
//            System.out.printf(" ===== %s ====\n", declaredField.getName());
            DBField annField = declaredField.getAnnotation(DBField.class);
//            System.out.println(annField.name());
//            System.out.println(annField.type());
//            System.out.println(annField.len());
//            System.out.println(annField.nullable());
            fields[i] = annField.name();
        }

        return String.format("select %s from %s",
                StringUtils.join(Arrays.asList(fields), ","),
                annTable.value());
    }
}
結果:
select name,pwd from user