• 全面解析java注解


    1:JDK自带注解

    @Override 表示覆盖或重写父类的方法;

    @Deprecated 表示该方法已经过时了。(当方法或是类上面有@Deprecated注解时,说明该方法或是类都已经过期不能再用,但不影响以前项目使用,提醒你新替代待的方法或是类。如果程序员不小心使用了它的元素,那么编译器会发出警告信息。

    @SuppressWarnings 表示忽略指定警告,比如@Suppvisewarnings("Deprecation")

    复制代码
     1 public interface Person {
     2     public String name();
     3     
     4     public int age();
     5     
     6     /*@Deprecated 表示该方法已经过时了*/
     7     @Deprecated
     8     public void sing();
     9     /*注:
    10      当方法或是类上面有@Deprecated注解时,
    11      说明该方法或是类都已经过期不能再用,
    12      但不影响以前项目使用,提醒你新替代待的方法或是类
    13      */
    14 }
    复制代码
    复制代码
     1 public class Test {
     2     /*@SuppressWarnings 表示忽略指定警告,比如@Suppvisewarnings("Deprecation")*/
     3     @SuppressWarnings("deprecation")
     4     public void sing(){
     5         Person p=new Child();
     6         
     7         p.sing();
     8     }
     9     
    10 }

    2:第三方注解

    如spring中的注解和mybatis中的注解

    3:按运行机制(注解存在于程序的那个阶段)将注解分为三类:源码注解(只在源码存在)、编译注解(在class文件中也存在)、运行时注解(在运行阶段仍然起作用)

    4:按照来源来分的话,有如下三类:
    1:JDK自带的注解(Java目前只内置了三种标准注解:@Override、@Deprecated、@SuppressWarnings,以及四种元注解:@Target、@Retention、@Documented、@Inherited)
    2:第三方的注解——这一类注解是我们接触最多和作用最大的一类
    3:自定义注解——也可以看作是我们编写的注解,其他的都是他人编写注解

    5:自定义注解语法要求

           1)使用@Interface关键字定义注解;

           2)成员以无参无异常方式声明;

           3)可以用default为成员指定一个默认值;

           4)成员类型是受限的,合法的类型包括原始类型及String、Class、Annotation、Enumeration;

           5)如果注解只有一个成员,则成员必须取名为value(),在使用时可以忽略成员名和赋值号(=);

           6)注解类可以没有成员,没有成员的注解称为标识注解;
    6:注解的注解(元注解)

    7: 注解配置

           @Target({ElementType.METHOD,ElementType.TYPE})
           CONSTRUCTOR:构造方法声明
           FIELD:字段声明
           LOACL_VARIABLE:局部变量声明
           METHOD:方法声明
           PACKAGE:包声明
           PARAMETER:参数声明
           TYPE:类或者接口声明

           @Retention(RetentionPolicy.RUNTIME)
           SOURCE:只在源码显示,编译时会丢弃

           CLASS:编译时会记录到class中,运行时忽略

           RUNTIME:运行时存在,可以通过反射读取

           @Inherited
           允许子类继承

           @Documented
           生成javadoc时会包含注解
    8: 使用自定义注解

           使用注解的语法:@<注解名>(<成员名1>=<成员值1>,<成员名2>=<成员值2>,...)

     9:解析注解

        概念:通过反射获取类,函数或成员上的运行时注解信息,从而实现动态控制控制程序运行的逻辑。

     一个例子:

    复制代码


    package com.demo.annotation;

    import java.lang.annotation.Annotation;
    import java.lang.reflect.Method;

    /**
    * 解析注解
    * @author Administrator
    * @date 2016年12月9日
    */
    public class Demo {
    public static void main(String[] args) {
           //1.使用类加载器加载类
           try {
           Class< ?> clazz = Class.forName("com.demo.annotation.AnnotationTest");
           //2.找到类上面的注解
           boolean flag1 = clazz.isAnnotationPresent(Description.class);
           if(flag1){
           //3.拿到注解实例
           Description description1 = (Description)clazz.getAnnotation(Description.class);
           System.out.println(description1.desc());
           System.out.println(description1.author());
           System.out.println(description1.age());
           }

        //4.解析找到方法上的注解
         Method[] methods = clazz.getMethods();
         for (Method method : methods) {
         boolean flag2 = method.isAnnotationPresent(Description.class);
          if(flag2){
        //5.拿到注解实例
         Description description2 = (Description)method.getAnnotation(Description.class);
             System.out.println(description2.desc());
             System.out.println(description2.author());
             System.out.println(description2.age());
       }
      }

    //另外一种解析方法
    for (Method method : methods) {
             Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
           if(annotation instanceof Description){
             Description description3 = (Description)annotation;
             System.out.println(description3.desc());
             System.out.println(description3.author());
             System.out.println(description3.age());
          }
         }
       }

      } catch (ClassNotFoundException e) {
         e.printStackTrace();
       }

      }

    }

    复制代码
     

    10;注解的继承只能作用在类上,方法上的注解不会被继承,Interface中的所有注解不会被继承。

    11:项目实战

    Table.java  类注解
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Table {
    String value();
    }

    Column.java 字段注解
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;

    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Column {

    String value();

    }

    Filter.java 实体类  使用注解
    @Table("user")
    public class Filter {
    @Column("id")
    private int id;

    @Column("userName")
    private String userName;

    @Column("email")
    private String email;

    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 getEmail() {
    return email;
    }

    public void setEmail(String email) {
    this.email = email;
    }

    }


    Test.java  解析注解
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;



    public class Test {
    public static String query(Object f){
    StringBuilder sb=new StringBuilder();
    //1.获取Class
    Class c=f.getClass();
    //2.获取Table的名字
    boolean isExist=c.isAnnotationPresent(Table.class);
    if(!isExist){
    return null;
    }
    Table t=(Table) c.getAnnotation(Table.class);
    String tableName=t.value();
    sb.append("select * form ").append(tableName).append(" where 1=1 ");
    //3.遍历所有的字段
    Field[] fArray=c.getDeclaredFields();
    for(Field field:fArray){
    //处理每个字段对应的sql
    boolean fExist=field.isAnnotationPresent(Column.class);
    if(! fExist){
    continue;
    }
    Column column=field.getAnnotation(Column.class);
    String columnName=column.value(); //数据库字段名
    String fieldName=field.getName();
    String getMethodName="get"+fieldName.substring(0, 1).toUpperCase()
    +fieldName.substring(1); //get方法名
    Object fieldValue=null;
    try {
    Method getMethod=c.getMethod(getMethodName);
    fieldValue=getMethod.invoke(f);//类字段值
    } catch (Exception e) {
    e.printStackTrace();
    }

    //拼装sql
    if(fieldValue==null || ((fieldValue instanceof Integer)&&((Integer)fieldValue==0)))
    continue;
    sb.append(" and ").append(fieldName);
    if(fieldValue instanceof String){
    if(((String) fieldValue).contains(",")){ //email
    String[] values=((String)fieldValue).split(",");
    sb.append(" in(");
    for(String v:values){
    sb.append("'").append(v).append("'").append(",");
    }
    sb.deleteCharAt(sb.length()-1);
    sb.append(")");
    }else
    sb.append("=").append("'").append(fieldValue).append("'");
    }else{
    sb.append("=").append(fieldValue);
    }
    }
    System.out.println(sb.toString());
    return sb.toString();
    }

    public static void main(String[] args){
    Filter f1=new Filter();
    f1.setId(10);
    Filter f2=new Filter();
    f2.setUserName("lucy");
    Filter f3=new Filter();
    f3.setEmail("liu@sina.com,zh@163.com,7777@qq.com");

    String sql1=query(f1);
    String sql2=query(f2);
    String sql3=query(f3);
    }

  • 相关阅读:
    数据结构之数组
    数据结构之链表
    MongoDB使用笔记
    数据结构之ArrayList
    java设计模式之--装饰者模式
    JAVA设计模式之--模板方法模式
    HashTable、HashMap、ConcurrentHashMap源码分析
    Docker使用笔记
    First-blog:解决mybatis 用mysql进行模糊搜索时,查不了中文问题
    css cursor: url() 使用火狐浏览器问题,鼠标没有效果
  • 原文地址:https://www.cnblogs.com/zyy1688/p/10282235.html
Copyright © 2020-2023  润新知