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

来源:互联网 发布:国家顶级域名 中文域名 编辑:程序博客网 时间:2024/05/29 04:28
  • 定义:
    注解(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为成员变量指定一个默认值    }
  • 元注解
@Target({ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.METHOD})// Target 注解的作用域   CONSTRUCTOR 构造方法声明,FIELD 字段声明,LOCAL_VARIABLE 局部变量声明 ,METHOD 方法声明,PACKAGE 包声明,PARAMETER 参数声明,TYPE 类接口。@Retention(RetentionPolicy.RUNTIME)//Retention 生命周期 SOURCE 只在源码显示,编译时会丢弃,CLASS 编译时会记录到class中,运行时忽略,RUNTIME 运行时存在,可以通过反射读取。@Inherited //Inherited 允许子类继承@Documented //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
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.FIELD})@Retention(RetentionPolicy.RUNTIME)public @interface Column {    String value();}
  • 自定义与表映射的类
package anotationDemo;/*** * java注解样例   利用注解将此表映射到数据库的表 * @author liaot * */@Table("t_user")public class Filter {    //定义字段属性    @Column("id")    private int id;    @Column("username")    private String username;    @Column("nickName")    private String nickName;    @Column("age")    private String age;    @Column("city")    private String city;    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 String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public String getCity() {        return city;    }    public void setCity(String city) {        this.city = city;    }}
  • (重点)使用自定义注解生成SQL语句
package anotationDemo;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import javax.management.Query;import com.sun.jndi.url.corbaname.corbanameURLContextFactory;import com.sun.org.apache.xpath.internal.operations.And;/*** * 自定义注解测试类 * @author liaot * */public class Test {    public static void main(String[] args) {        Filter f1 = new Filter();        f1.setId(1); //查询id为1的用户        Filter f2 = new Filter();        f1.setUsername("lili"); //查询用户名为lili的用户        Filter f3 = new Filter();        f3.setCity("衡阳,长沙,永州"); //查询地点在这三个城市之间的        String sql1 = query(f1);        String sql2 = query(f2);        String sql3 = query(f3);        System.out.println(sql1);        System.out.println(sql2);        System.out.println(sql3);    }    private static String query(Object f) {        StringBuilder sql = new StringBuilder();        //获取到class        Class c1 = f.getClass();        //获取table的名字        boolean exists = c1.isAnnotationPresent(Table.class);        if(!exists) {            return null;        }        Table t = (Table)c1.getAnnotation(Table.class);        //定义表名        String tableName = t.value();        sql.append("select * from ").append(tableName).append(" where 1=1 ");        //遍历所有的字段        Field[] fields = c1.getDeclaredFields();        for (Field field : fields) {            //判断是否存在这个注解            boolean Fexists = field.isAnnotationPresent(Column.class);            if(!Fexists) {                continue;            }            //获取注解            Column column = field.getAnnotation(Column.class);            String ColumuName = column.value();            //获取字段的值            String fieldName = field.getName();            String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);            Method method = null;            Object ColumuValue = null;            try {                method = c1.getMethod(getMethodName);                ColumuValue = method.invoke(f);            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {                e.printStackTrace();            }            //int型不需要加单引号,String型需要加单引号            if(ColumuValue instanceof Integer && (int)ColumuValue != 0){                sql.append("and " + ColumuName + " = " + ColumuValue + " ");            }else if(ColumuValue instanceof String){                if( ((String) ColumuValue).contains(",") ){                    String[] values = ((String) ColumuValue).split(",");                    sql.append("and " + ColumuName + " in (");                    for(int i=0; i<values.length; i++) {                        sql.append("'").append(values[i]).append(" ',");                    }                    sql.deleteCharAt(sql.length() -1);                    sql.append(")");                 }else{                    sql.append("and " + ColumuName + " = '" + ColumuValue + "' ");                }            }        }        return sql.toString();    }}
  • 代码下载地址:Github下载
1 0
原创粉丝点击