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
@Documented
public @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
@Documented
public @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();
}
}

annotation使用示例的更多相关文章

  1. Java 基础之认识 Annotation

    Java 基础之认识 Annotation 从 JDK 1.5 版本开始,Java 语言提供了通用的 Annotation 功能,允许开发者定义和使用自己的 Annotation 类型.Annotat ...

  2. Java注解(Annotation)详解

    转: Java注解(Annotation)详解 幻海流心 2018.05.23 15:20 字数 1775 阅读 380评论 0喜欢 1 Java注解(Annotation)详解 1.Annotati ...

  3. 合理使用Android提供的Annotation来提高代码的质量

    概述 Java语言提供了Annotation的机制,让描述性的元数据能够和代码共存.通常我们可以利用Annotation,来做一些标志性的说明.然而Annotation必须和相应的解析工具一起才能工作 ...

  4. java注解(转并做修改)

    本文由 ImportNew - 人晓 翻译自 idlebrains.欢迎加入翻译小组.转载请见文末要求. 自Java5.0版本引入注解之后,它就成为了Java平台中非常重要的一部分.开发过程中,我们也 ...

  5. Java注解的原理

    自Java5.0版本引入注解之后,它就成为了Java平台中非常重要的一部分.开发过程中,我们也时常在应用代码中会看到诸如@Override,@Deprecated这样的注解.这篇文章中,我将向大家讲述 ...

  6. java ee7 配置文件

    java ee7 配置文件 1. 项目目录 # ee pom.xml      Maven构建文件 /src/main/java      Java源文件 /src/main/resource     ...

  7. org.Hs.eg.db包简介(转换NCBI、ensemble等数据库中基因ID,symbol等之间的转换)

    1)安装载入 ------------------------------------------- if("org.Hs.eg.db" %in% rownames(install ...

  8. java websocket @ServerEndpoint注解说明

    http://www.blogjava.net/qbna350816/archive/2016/07/24/431302.html https://segmentfault.com/q/1010000 ...

  9. javax.persistence.EntityNotFoundException: Unable to find报错

    这类错id 可能是10,可能是27,也可能是其他数字 错误描述: javax.persistence.EntityNotFoundException: Unable to find 某个类 with ...

随机推荐

  1. day14 迭代器,生成器,函数的递归调用

    1.什么是迭代器 迭代是一个重复的过程,但是每次重复都是基于上一次重复的结果而继续 迭代取值的工具 2.为什么要用迭代器 迭代器的优点 ​ ①不依赖于索引取值 ​ ②更节省内存 缺点: ​ 1.不如按 ...

  2. (转)ios 代码规范

    转自http://blog.csdn.net/pjk1129/article/details/45146955 引子 在看下面之前,大家自我检测一下自己写的代码是否规范,代码风格是否过于迥异阅读困难? ...

  3. 菜鸟的《Linux程序设计》学习—shell script

    1. 认识shell script shell script是利用shell的功能缩写的一个"程序",这个程序是使用纯文本文件,将一些shell的语法与命令(含外部命令)写在里面, ...

  4. WPF IP地址输入控件的实现

    一.前言 WPF没有内置IP地址输入控件,因此我们需要通过自己定义实现. 我们先看一下IP地址输入控件有什么特性: 输满三个数字焦点会往右移 键盘←→可以空光标移动 任意位置可复制整段IP地址,且支持 ...

  5. 通过日志动态查看正在执行的mysql语句

    通过日志动态查看正在执行的mysql语句 :tail -f /tmp/general_log.log

  6. 82. Spring Boot – 启动彩蛋【从零开始学Spring Boot】

    我们在[28. SpringBoot启动时的Banner设置 ] 这一小节介绍过设置Spring Boot的Banner,但是实际当中,我们希望做的更漂亮,所以也就有了这小节Spring Boot-启 ...

  7. 【C#】堆、栈和堆栈的区别

    导读:今天看视频,就看到了堆.栈这一块了.记得当年初相见(VB视频),劈头盖脸一阵蒙,什么都不知道,那时候师傅叫我挂起来,说我随着学习的进度,慢慢的就会懂了.现在,学到了这里,想着自己对自己从前的问题 ...

  8. POJ-2594 Treasure Exploration,floyd+最小路径覆盖!

                                                 Treasure Exploration 复见此题,时隔久远,已忘,悲矣! 题意:用最少的机器人沿单向边走完( ...

  9. EasyUI combogrid 赋多个值

    var values = []; for (var i = 0; i < rows.length; i++) { if (rows[i].id>0 ) { values.push('' + ...

  10. 深入了解类加载过程及Java程序执行顺序

    前言 在Java中,静态 Static关键字使用十分常见 本文全面 & 详细解析静态 Static关键字,希望你们会喜欢 目录 1. 定义 一种 表示静态属性的 关键字 / 修饰符 2. 作用 ...