博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
annotation使用示例
阅读量:5835 次
发布时间:2019-06-18

本文共 6111 字,大约阅读时间需要 20 分钟。

annotation使用示例

学习了:https://www.imooc.com/learn/456

Annotation编写规则:@Target,@Retention,设置一些String、int属性;@Inherited只能继承类的;只有一个属性只能叫value;

使用的时候使用反射机制,annotation中的方法就是在反射的时候取值的方法;

代码:

Annotation Column:

package com.imooc.test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Column {    String value();}

Annotation Table:

package com.imooc.test;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Table {    String value();}

Filter:

package com.imooc.test;@Table("user")public class Filter {    @Column("id")    private int id;    @Column("user_name")    private String userName;    @Column("nick_name")    private String nickName;    @Column("age")    private int age;    @Column("city")    private String city;    @Column("email")    private String email;    @Column("mobile")    private String mobile;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getNickName() {        return nickName;    }    public void setNickName(String nickName) {        this.nickName = nickName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getMobile() {        return mobile;    }    public void setMobile(String mobile) {        this.mobile = mobile;    }}

Filter2:

package com.imooc.test;@Table("department")public class Filter2 {    @Column("id")    private int id;    @Column("name")    private String name;    @Column("leader")    private String leader;    @Column("amount")    private int amount;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getLeader() {        return leader;    }    public void setLeader(String leader) {        this.leader = leader;    }    public int getAmount() {        return amount;    }    public void setAmount(int amount) {        this.amount = amount;    }    }

Test:

package com.imooc.test;import java.lang.reflect.Field;import java.lang.reflect.Method;public class Test {    public static void main(String[] args) {        Filter f1 = new Filter();        f1.setId(10); // 表示查询id为10的用户                Filter f2 = new Filter();        f2.setUserName("lucy"); // 表示查询用户名为lucy的用户        f2.setAge(18);                Filter f3 = new Filter();        f3.setEmail("liu@sina.com.cn"); // 查询邮箱为其中任意一个的用户 ,zh@163.com,77777@qq.com                String sql1 = query(f1);        String sql2 = query(f2);        String sql3 = query(f3);                System.out.println(sql1);        System.out.println(sql2);        System.out.println(sql3);                        Filter2 filter2 = new Filter2();        filter2.setAmount(10);        filter2.setName("技术部");        System.out.println(query(filter2));            }    private static String query(Object f) {        StringBuilder builder = new StringBuilder();        // 1, 获取到class        Class c = f.getClass();        // 2, 获取到table的名字        boolean exists = c.isAnnotationPresent(Table.class);        if(!exists) {            return null;        }        Table t = (Table) c.getAnnotation(Table.class);        String tableName = t.value();        builder.append("select * from ").append(tableName).append(" where 1=1");        // 3, 遍历所有的字段        Field[] fArray = c.getDeclaredFields();        for (Field field : fArray) {            // 4. 处理每个字段对应的sql            // 4.1 拿到字段名            boolean fExists = field.isAnnotationPresent(Column.class);            if(!fExists) {                continue;            }            Column column = field.getAnnotation(Column.class);            String columnName = column.value();            // 4.2 拿到字段的值            String fieldName = field.getName();            String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1);            Method getMethod;            Object fieldValue=null;            try {                getMethod = c.getMethod(getMethodName);                fieldValue = getMethod.invoke(f);            } catch (Exception e) {                e.printStackTrace();            }              // 4.3 拼装sql            if(fieldValue == null || (fieldValue instanceof Integer && (Integer)fieldValue == 0)) {                continue;            }            builder.append(" add ").append(fieldName);            if(fieldValue instanceof String) {                if(((String)fieldValue).contains(",")) {                    String[] values = ((String)fieldValue).split(",");                    builder.append("in(");                    for (String v : values) {                        builder.append("'").append(v).append("',");                    }                    builder.deleteCharAt(builder.length()-1);                    builder.append(")");                }else {                    builder.append("=").append("'").append(fieldValue).append("'");                }            } else if (fieldValue instanceof Integer) {                builder.append("=").append(fieldValue);            }        }        return builder.toString();    }}

 

转载地址:http://lpucx.baihongyu.com/

你可能感兴趣的文章
防止 JavaScript 自动插入分号
查看>>
Java工厂模式
查看>>
TMS320F28335项目开发记录5_28335之CCS编程基础
查看>>
hive列转行
查看>>
GridView编辑删除操作
查看>>
二叉树的三种遍历的应用(表达式,求深度,叶子数,结点数,二叉树的建立,复制)...
查看>>
说说JSON和JSONP,也许你会豁然开朗
查看>>
依据道路的shape获得high_cross和low_cross
查看>>
SAE+Java+jetty
查看>>
Java 权限框架 Shiro 实战一:理论基础
查看>>
大话数据结构之四(串)
查看>>
加热炉简是新来的整个系统的板
查看>>
Mockito使用注意事项
查看>>
[LeetCode] Palindrome Linked List 回文链表
查看>>
UVA - 825Walking on the Safe Side(dp)
查看>>
android大概是通过logcat拦截Log
查看>>
android HDMI 清晰度 分辨率
查看>>
Codeforces 480C Riding in a Lift dp
查看>>
JQuery发送Put、Delete请求 - 摘自网络
查看>>
Android基于mAppWidget实现手绘地图(九)–如何处理地图对象的touch事件
查看>>