java基础注解——2020/09/11

代码文档中的一些注解解释

自定义注解+反射=自定义校验

先定义注解类

package com.zs.anotation;


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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.METHOD})
public @interface MyAnnotation {
    String checkFiled() default "";
    boolean checkMethod() default true;
}

 

给对应实体加上注解

package com.zs.anotation;


public class User {
    @MyAnnotation(checkFiled = "eamil",checkMethod = false)
    private String email;
    @MyAnnotation(checkFiled = "userName",checkMethod = false)
    private String UserName;

    public User() {
    }

    public User(String email, String userName) {
        this.email = email;
        UserName = userName;
    }

    public String getEmail() {
        return email;
    }

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

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    @Override
    public String toString() {
        return "User{" +
                "email='" + email + '\'' +
                ", UserName='" + UserName + '\'' +
                '}';
    }
}

 

获取对象多有属性,根据属性获取其对应的注解,根据添加的注解自定义规则校验

package com.zs.anotation;

import java.lang.reflect.Field;

public class TestClass {
    public static void main(String[] args) {
        //获取对象的所有属性
        Field[] fields = new User().getClass().getDeclaredFields();
        for(Field fie : fields){
            //获取到对应字段上的所有注解
            MyAnnotation annotation = fie.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.checkFiled());
            //之后根据字段名获取方法。。。。。巴拉巴拉
        }

    }
}

 

 

元注解:修饰注解的注解(4个)

 @Retention:注解的保留位置         

    @Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含

    @Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,

    @Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Target:注解的作用目标        

    @Target(ElementType.TYPE)   //接口、类、枚举、注解

    @Target(ElementType.FIELD) //字段、枚举的常量

    @Target(ElementType.METHOD) //方法

    @Target(ElementType.PARAMETER) //方法参数

    @Target(ElementType.CONSTRUCTOR)  //构造函数

    @Target(ElementType.LOCAL_VARIABLE)//局部变量

    @Target(ElementType.ANNOTATION_TYPE)//注解

    @Target(ElementType.PACKAGE) ///包   

@Document:说明该注解将被包含在javadoc中

 @Inherited:说明子类可以继承父类中的该注解

 

jdk1.8新增注解3个

@Repeatable可重复注解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值