🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 注解Annotation 特别在系统框架的搭建过程中,往往需要很多的配置文件,比如数据源、IOC、AOP、框架本身的映射(如 Hibernate 表与字段),需要的配置文件会导致系统越来越复杂,而且维护很不方便,一旦配置文件出错,很容易导致系统无法运行。 在 JDK1.5 以后,引入了注解 Annotation 技术,极大的方便了配置化的编程,很多的技术和框架都使用了技术,如 Servlet/Filter/Spring/SpringMVC/Hibernate/Nutz。 ## 定义 ~~~ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) @Documented public @interface Column { boolean hump() default true; String name() default ""; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented public @interface Table { String value(); } ~~~ ## 应用 ~~~ package com.ntqingniao.annotation; import java.util.Date; @Table("t_sys_account") public class Account { @Column(name="ID") private Integer id; @Column private String name; @Column(name="PASSWOR") private String password; @Column(hump=true) private Date createTime; private String desc; } ~~~ ## 解析注解数据 ~~~ package com.ntqingniao.annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Date; public class Client2 { public static void main(String[] args) throws Exception { Account account = new Account(); account.setId(10); account.setName("Tom"); account.setPassword("123456"); account.setCreateTime(new Date()); Student stu = new Student(); stu.setId(12); stu.setName("helen"); stu.setPassword("aaaaaa"); stu.setDesc("hello,helen"); stu.setCreateTime(new Date()); System.out.println(gerInsertSql(account)); System.out.println(gerInsertSql(stu)); // insert into t_sys_account(ID,NAME,PASSWORD,CREATE_TIME) values(10, // "Tom", "123456", "20170711"); } public static String gerInsertSql(Object account) throws Exception { String sql = "insert into "; String values = ""; Class<?> c = null; c = account.getClass(); Table table = c.getAnnotation(Table.class); String tableName = table.value(); sql += tableName + "("; Field[] fields = c.getDeclaredFields(); for (Field field : fields) { Column column = field.getAnnotation(Column.class); String columnName = field.getName(); if (null != column) { // 首先判断hump属性是否为true columnName = Client3.toHump(columnName); // 否则取name属性值 String cn = column.name(); if (null != cn && !cn.trim().equals("")) { columnName = cn; } else { // 如果name属性值为空,则取字段名 } sql += columnName + ","; // 获取字段的属性值,并拼写到values变量中 Method getMethod = c.getMethod("get" + Client3.captureName(field.getName())); Object obj = getMethod.invoke(account); values += Client3.changeToSql(obj) + ","; } } sql = sql.substring(0, sql.length() - 1) + ")" + " values(" + values.substring(0, values.length() - 1) + ")"; return sql; } } ~~~