自定义注解demo


package
com.entity; import com.annocation.Col; import com.annocation.Table; @Table(name = "user")//user为数据库中表名 //定义User属性 public class User { @Col(name = "userName")//user表中列名 private String userName; @Col(name = "id")//user表中列名 private int id; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
package com.annocation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)//1.

@Retention(RetentionPolicy.RUNTIME)//2.自定义注解  编译完,运行时有效
//
public @interface Table {
    //定义方法 表名称
    String name();

}
package com.annocation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
//字段名、列名
public @interface Col {
    //列名
    String name();

}
package com.main;

import java.lang.reflect.Field;

import com.annocation.Col;
import com.annocation.Table;

public class Test {
    public static void main(String[] args) throws ClassNotFoundException {
        // 定义sql语句对象,追加
        StringBuffer sb = new StringBuffer();
        // select 语句开头
        sb.append("select ");
        // 加载User类
        Class<?> forname = Class.forName("com.entity.User");
        // 拿到成员属性
        Field[] declaredFields = forname.getDeclaredFields();
        // 遍历属性
        for (int i = 0; i < declaredFields.length; i++) {
            // 拿到注解获取Col name值
            Col col = declaredFields[i].getAnnotation(Col.class);
            String name = col.name();
            sb.append(name);
            //判断是否为最后一个属性,最后一个追加from不是追加,
            if (i == declaredFields.length - 1) {
                sb.append(" from ");
            } else {
                sb.append(" ,");
            }
        }
        // 拿到注解获取Table name值
        Table table = forname.getAnnotation(Table.class);
        String name = table.name();
        sb.append(name);
        // 输出sql语句
        System.out.println(sb.toString());
    }

}

         


posted @ 2018-12-03 10:23  朱忠玉  阅读(110)  评论(0)    收藏  举报