Java注解

Java中注解的定义与使用

Java注解基本概念

@Override @Deprecated @Autowired @RestController @GetMapping 

如上等等,都是注解

常见常用注解

  • @Override
  • @Autowired
  • @Service
  • Repository
  • @Mapper
  • @TableLogic
  • …….

注解分类

按运行机制分

  • 源码注解
  • 编译时注解:@Overrride
  • 运行时注解:@Autowired

按来源分

  • 来自jdk的注解
  • 来自第三方的注解
  • 自定义的注解

特别的

  • 元注解:为注解注解的"注解"

自定义注解

语法

@Documented
@Target({ElementType.METHOD,ElementType.TYPE})
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface Lai {

    int value() default 0;

    String name() default "Lai";

    String gender();

}
  • 使用@interface标识
  • 成员以无参数无异常方式声明
  • 可以使用default为成员指定一个默认值
  • 成员类型受限,可以选择基本数据类型,String,Class,Annotation,Enumeration
  • 若注解只有一个成员,建议声明为value(),使用时可以忽略等号赋值号
  • 可以没有成员,没有成员称为标识注解

元注解

  • @Target:标明注解作用域,类型为ElementType
    • CONSTRUCTOR:构造方法
    • FIELD:字段
    • LOCAL_VARIABLE:局部变量
    • METHOD:方法
    • PACKAGE:包
    • PARAMETER:参数
    • TYPE:类,接口
  • @Retention:标注注解生命周期,类型为RetentionPolicy
    • SOURCE:源码注解
    • CLASS:编译注解
    • RUNTIME:运行时注解
  • @Inherited:是否允许子类继承
  • @Documented:生成Javadoc是否包含注解信息

解析注解

@Lai(gender = "男")
public class Anno {

    @Lai(gender = "女")
    public static void main(String[] args) {

    }
}

解析:

public static void main(String[] args) {
        Lai lai;
        try {
            //加载对应的类
            Class anno = Class.forName("Anno");
            //判断是否存在注解
            boolean present = anno.isAnnotationPresent(Lai.class);
            if(present){
                lai = (Lai) anno.getAnnotation(Lai.class);
                System.out.println(lai.gender());
            }

            //方法上的注解
            Method[] methods = anno.getMethods();
            for(Method method: methods){
                if(method.isAnnotationPresent(Lai.class)){
                    lai = method.getAnnotation(Lai.class);
                    System.out.println(lai.gender());
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

注解使用举例

简单的sql生成

实体类:

@Table("t_user")
public class User {

    @Column("id")
    private int id;
    @Column("name")
    private String name;
    @Column("password")
    private String password;
    @Column("email")
    private String email;
    @Column("phone")
    private String phone;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

生成sql方法:

public static void main(String[] args) {
        User user1 = new User();
        user1.setId(1);

        User user2=new User();
        user2.setId(2);
        user2.setName("啦啦啦");

        User user3 = new User();
        user3.setEmail("xxxx@qq.com");

        System.out.println(query(user1));
        System.out.println(query(user2));
        System.out.println(query(user3));
    }

    public static String query(User user){
        StringBuilder sb = new StringBuilder();
        //获取class
        Class c = user.getClass();
        if(!c.isAnnotationPresent(Table.class)){
            return null;
        }
        Table t = (Table) c.getAnnotation(Table.class);
        String tableName = t.value();
        sb.append("select * from " + tableName).append(" where 1=1 ");
        //遍历字段,判断是否有值
        Field[] fields = c.getDeclaredFields();
        for(Field field: fields){
            if(!field.isAnnotationPresent(Column.class)){
                continue;
            }
            Column column = field.getAnnotation(Column.class);
            String columnName = column.value();
            //获取字段值
            String fieldName = field.getName();
            String getFieldName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
            Object fieldValue;
            try {
                Method method = c.getMethod(getFieldName);
                fieldValue =  method.invoke(user, null);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
            //拼接sql
            if(fieldValue==null){
                continue;
            }
            if(fieldValue instanceof Integer && Integer.valueOf(0).equals(fieldValue)){
                continue;
            }
            sb.append(" and ").append(fieldName).append(" = ").append(fieldValue);
        }
        return sb.toString();
    }
版权所有,转载请注明出处!
渝ICP备2022006471
Built with Hugo
主题 StackJimmy 设计