健康一贴灵,专注医药行业管理信息化

转:java注解详解(注解项目实战)

原文地址:http://blog.csdn.net/c1481118216/article/details/52911263

  • 定义:

注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。

  • 作用分类:

①编写文档:通过代码里标识的元数据生成文档【生成文档doc文档】
② 代码分析:通过代码里标识的元数据对代码进行分析【使用反射】
③编译检查:通过代码里标识的元数据让编译器能够实现基本的编译检查【Override】

JDK内置系统注解:

@Override 用于修饰此方法覆盖了父类的方法;
@Deprecated 用于修饰已经过时的方法;
@suppressWarings("deprecation") 用于通知java编译器忽略特定的编译警告。
  •  注解的分类 

1、按照运行机制分为
源码注解:注解只在源码中存在,编译成.class文件就不存在了
编译时注解:注解在源码和.class文件中都存在(如:JDK内置系统注解)
运行时注解:在运行阶段还起作用,甚至会影响运行逻辑的注解(如:Spring中@Autowried)
2、按照来源分为
JDK内置系统注解、元注解、自定义注解、第三方注解

  • 自定义注解:

1.成员类型是受限的,合法的类型包括原始类型及String,Calss,Anootation,Enumreation
2.如果注解已有一个成员,则成员名必须取名为Vaue(),在使用的时可以忽略成员名和赋值号(=)
3.注解类可以没有成员,没有成员的注解称为标识注解

public @interface Description{//使用@interface关键字注解
    String name();//成员以无参无异常方式声明
    String author();
    int age() default 19;//可以用default为成员变量指定一个默认值
    }
  • 元注解:
1 @Target({ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.METHOD})
2 // Target 注解的作用域   CONSTRUCTOR 构造方法声明,FIELD 字段声明,LOCAL_VARIABLE 局部变量声明 ,METHOD 方法声明,PACKAGE 包声明,PARAMETER 参数声明,TYPE 类接口。
3 @Retention(RetentionPolicy.RUNTIME)
4 //Retention 生命周期 SOURCE 只在源码显示,编译时会丢弃,CLASS 编译时会记录到class中,运行时忽略,RUNTIME 运行时存在,可以通过反射读取。
5 @Inherited 
6 //Inherited 允许子类继承
7 @Documented 
8 //Documented 生成javadoc的时候包含注解
  • 注解项目实战
    • 这里写图片描述

  • 自定义注解(Table)
package anotationDemo;

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

/***
 * 数据库表的注解
 * @author liaot
 *  */
@Target({ElementType.TYPE}) //设置作用域为类 接口
@Retention(RetentionPolicy.RUNTIME) //设置生命周期为运行时
public @interface Table {
    String value();  //表名
}
  • 自定义注解Column
 1 package anotationDemo;
 2 
 3 import java.lang.annotation.ElementType;
 4 import java.lang.annotation.Retention;
 5 import java.lang.annotation.RetentionPolicy;
 6 import java.lang.annotation.Target;
 7 
 8 /***
 9  * 自定义注解 ,用来映射字段名
10  * @author liaot
11  *
12  */
13 @Target({ElementType.FIELD})
14 @Retention(RetentionPolicy.RUNTIME)
15 public @interface Column {
16     String value();
17 }

 

  • 自定义与表映射的类
 1 package anotationDemo;
 2 /***
 3  * java注解样例   利用注解将此表映射到数据库的表
 4  * @author liaot
 5  *
 6  */
 7 @Table("t_user")
 8 public class Filter {
 9     //定义字段属性
10     @Column("id")
11     private int id;
12     @Column("username")
13     private String username;
14     @Column("nickName")
15     private String nickName;
16     @Column("age")
17     private String age;
18     @Column("city")
19     private String city;
20 
21 
22     public int getId() {
23         return id;
24     }
25     public void setId(int id) {
26         this.id = id;
27     }
28     public String getUsername() {
29         return username;
30     }
31     public void setUsername(String username) {
32         this.username = username;
33     }
34     public String getNickName() {
35         return nickName;
36     }
37     public void setNickName(String nickName) {
38         this.nickName = nickName;
39     }
40     public String getAge() {
41         return age;
42     }
43     public void setAge(String age) {
44         this.age = age;
45     }
46     public String getCity() {
47         return city;
48     }
49     public void setCity(String city) {
50         this.city = city;
51     }
52 
53 }
  • (重点)使用自定义注解生成SQL语句
 1 package anotationDemo;
 2 
 3 import java.lang.reflect.Field;
 4 import java.lang.reflect.InvocationTargetException;
 5 import java.lang.reflect.Method;
 6 
 7 import javax.management.Query;
 8 
 9 import com.sun.jndi.url.corbaname.corbanameURLContextFactory;
10 import com.sun.org.apache.xpath.internal.operations.And;
11 
12 /***
13  * 自定义注解测试类
14  * @author liaot
15  *
16  */
17 public class Test {
18     public static void main(String[] args) {
19         Filter f1 = new Filter();
20         f1.setId(1); //查询id为1的用户
21 
22         Filter f2 = new Filter();
23         f1.setUsername("lili"); //查询用户名为lili的用户
24 
25         Filter f3 = new Filter();
26         f3.setCity("衡阳,长沙,永州"); //查询地点在这三个城市之间的
27 
28         String sql1 = query(f1);
29         String sql2 = query(f2);
30         String sql3 = query(f3);
31 
32         System.out.println(sql1);
33         System.out.println(sql2);
34         System.out.println(sql3);
35 
36     }
37 
38     private static String query(Object f) {
39         StringBuilder sql = new StringBuilder();
40         //获取到class
41         Class c1 = f.getClass();
42         //获取table的名字
43         boolean exists = c1.isAnnotationPresent(Table.class);
44         if(!exists) {
45             return null;
46         }
47         Table t = (Table)c1.getAnnotation(Table.class);
48         //定义表名
49         String tableName = t.value();
50         sql.append("select * from ").append(tableName).append(" where 1=1 ");
51         //遍历所有的字段
52         Field[] fields = c1.getDeclaredFields();
53         for (Field field : fields) {
54             //判断是否存在这个注解
55             boolean Fexists = field.isAnnotationPresent(Column.class);
56             if(!Fexists) {
57                 continue;
58             }
59             //获取注解
60             Column column = field.getAnnotation(Column.class);
61             String ColumuName = column.value();
62             //获取字段的值
63             String fieldName = field.getName();
64             String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
65             Method method = null;
66             Object ColumuValue = null;
67             try {
68                 method = c1.getMethod(getMethodName);
69                 ColumuValue = method.invoke(f);
70 
71             } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
72                 e.printStackTrace();
73             }
74             //int型不需要加单引号,String型需要加单引号
75             if(ColumuValue instanceof Integer && (int)ColumuValue != 0){
76                 sql.append("and " + ColumuName + " = " + ColumuValue + " ");
77             }else if(ColumuValue instanceof String){
78                 if( ((String) ColumuValue).contains(",") ){
79                     String[] values = ((String) ColumuValue).split(",");
80                     sql.append("and " + ColumuName + " in (");
81                     for(int i=0; i<values.length; i++) {
82                         sql.append("'").append(values[i]).append(" ',");
83                     }
84                     sql.deleteCharAt(sql.length() -1);
85                     sql.append(")"); 
86                 }else{
87                     sql.append("and " + ColumuName + " = '" + ColumuValue + "' ");
88                 }
89             }
90         }
91         return sql.toString();
92     }
93 }

 

请注明原文地址:http://blog.csdn.net/c1481118216

 

posted @ 2018-02-02 16:17  一贴灵  阅读(3592)  评论(0编辑  收藏  举报
学以致用,效率第一