Java自定义注解的使用

来源:互联网 发布:阿里云域名优惠 2017 编辑:程序博客网 时间:2024/05/01 21:34

最近学习了一下Java的自定义注解,终于知道了框架那些注解是咋个写出来的了,以后我也可以自己写框架,自己定义注解,听着是不是很牛的样子?不要心动,赶快行动,代码很简单,一起来学习一下吧!

这个例子是模仿框架的一个对sql拼装的例子,用注解实现对model也就是实体类的注释,就可以写出查询该字段的sql.好了,废话少说,一看代码便知。大家可以根据自己的需求修改。

package com.annotation.demo;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;/** * 1. @interface 定义注解关键字 * 2. 元注解: *     @Target:注解的作用域 *     ElementType *         TYPE:类接口声明 *         CONSTURCTOR:构造方法声明 *         FILED:字段声明 *         LOCAL_VARIABLE:局部变量声明 *         METHOD:方法声明 *         PARCKAGE:包声明 *         PARMETER:参数声明 *     @Retention:注解的声明周期 *     RetentionPolicy *         RUNTIME:运行时存在,可以通过反射读取 *         SOURCE:只在源码显示,编译时会丢弃 *         CLASS:编译时会记录到class中,运行时忽略 *     @Inherited:允许子类继承 *     @Documented:生成javadoc时会包含注解 *   3. 使用自定义注解 *   @<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>,...) *   如: *   @MyAnnotation(name="Stephen.Huang", date="2015-7-30") *   public void MyMethod() { *       //TODO *   } *  *  * @author Stephen Huang * @see http://blog.csdn.net/u010571844 * */@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface Table {/** * 1.成员以无参无异常声明 * 2.可以用default为成员指定一个默认值,如:int age() default 18; * 3.成员类型是受限制的,合法的类型包括原始类型及String,Class,Annotation, Enumeration。 * 4.如果注解只有一个成员,则成员名必须取名为value(),在使用时可以忽略成员名和‘=’。 * 5.注解类可以没有成员,没有成员的注解称为标注注解。 * @return */String value();}
2.再定义数据table中字段的注解Clounm

package com.annotation.demo;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** *  * @author Stephen Huang * */@Target({ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Column {String value();}

3.定义User实体类

package com.annotation.demo;@Table("user")public class User {@Column("id")    private Integer id;@Column("user_name")    private String userName;@Column("email")    private String email;    public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}}

4.测试

package com.annotation.demo;import java.lang.reflect.Field;import java.lang.reflect.Method;/** *  * @author Stephen Huang * */public class test {/** * @param args */public static void main(String[] args) {User user1 = new User();user1.setId(1);//search user id 1User user2 = new User();user2.setUserName("Stephen");//search user name 'stephen'User user3 = new User();user3.setEmail("stephenhuang@qq.com, stephenhuang@163.com");//search user email ''String sql1 = query(user1);String sql2 = query(user2);String sql3 = query(user3);System.out.println(sql1);System.out.println(sql2);System.out.println(sql3);}private static String query(Object f) {StringBuffer sb = new StringBuffer();//1.get classClass c = f.getClass();//2.get table nameboolean exits = c.isAnnotationPresent(Table.class);if (!exits) {return null;}Table t = (Table) c.getAnnotation(Table.class);String tableName = t.value();sb.append("select * from ").append(tableName).append(" where 1=1");Field[] fArray = c.getDeclaredFields();for (Field field : fArray) {boolean fexits = field.isAnnotationPresent(Column.class);if (!fexits) {continue;}Column clolumn = field.getAnnotation(Column.class);String clolumnName = clolumn.value();String filedName = field.getName();String getMethodName = "get" + filedName.substring(0, 1).toUpperCase()+ filedName.substring(1, filedName.length());Object filedValue = null;try {Method getMethod = c.getMethod(getMethodName);filedValue = getMethod.invoke(f);} catch (Exception e) {e.printStackTrace();}if (filedValue == null || (filedValue instanceof Integer && (Integer)filedValue == 0)){continue;}sb.append(" and ").append(filedName);if (filedValue instanceof String) {if (((String) filedValue).contains(",")) {String[] filedValues = ((String) filedValue).split(",");sb.append(" in (");for (String value : filedValues) {sb.append("'").append(value).append("',");}sb.deleteCharAt(sb.length() - 1);sb.append(")");} else {    sb.append(" = '").append(filedValue).append("'");}} else {sb.append(" = ").append(filedValue);}}return sb.toString();}}

5.测试结果

select * from user where 1=1 and id = 1select * from user where 1=1 and userName = 'Stephen'select * from user where 1=1 and email in ('stephenhuang@qq.com',' stephenhuang@163.com')



0 0
原创粉丝点击