java 注解(annotation)

java注解一般和反射一起使用
一下是一个使用注解和反射实现自动生成sql 语句的例子:

注解类Table:

package anno.cla;

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

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

    String value();

}

注解类 Column:

package anno.cla;

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 Column {

    String value();

}

实体类 User:

package anno.entity;

import java.util.Date;

import anno.cla.Column;
import anno.cla.Table;

@Table("t_user")
public class User {

    @Column("id")
    private Integer id;

    @Column("name")
    private String name;

    @Column("age")
    private Integer age;

    @Column("phone")
    private String phone;

    @Column("birthday")
    private Date birthday;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

}

具体实现类:

package anno;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import anno.cla.Column;
import anno.cla.Table;
import anno.entity.User;

// 注解测试
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        User user1 = new User();
        user1.setId(3);

        User user2 = new User();
        user2.setName("name");

        System.out.println(sqlQuery(user1));
        System.out.println(sqlQuery(user2));

    }

    private static String sqlQuery(User user){
        StringBuffer sqlBuffer = new StringBuffer();
        Class cla = user.getClass();

        //判断是否有 table 注解
        boolean tableExists = cla.isAnnotationPresent(Table.class);
        if(!tableExists){
            return null;
        }

        Table t = (Table) cla.getAnnotation(Table.class);
        String tableName = t.value();
        System.out.println("tableName: " + tableName);
        sqlBuffer.append("select * from ").append(tableName).append(" where 1 = 1 ");

        //遍历所有属性
        Field[] fields = cla.getDeclaredFields();
        for(Field f: fields){
            boolean fExists = f.isAnnotationPresent(Column.class);
            if(fExists){
                Column column = f.getAnnotation(Column.class);
                //获取字段的值
                String fieldName = f.getName();
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    Method getMethod = cla.getMethod(getMethodName);
                    Object fieldObj = getMethod.invoke(user);
                    if(fieldObj instanceof Integer && fieldObj != null && (Integer)fieldObj != 0 ){
                        sqlBuffer.append(fieldName).append("=").append((Integer) fieldObj);
                    } else if(fieldObj instanceof String && fieldObj != null){
                        sqlBuffer.append(fieldName).append("=").append((String)fieldObj);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            } else{
                continue;
            }
        }
        return sqlBuffer.toString();
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值