java自定义注解

本文介绍了Java中的注解(Annotation)使用,包括元注解如@Retention、@Target,以及如何创建和使用自定义注解。通过一个User类和UserFactory示例展示了注解在字段和方法上的应用,并提供了注解解析器来设置对象属性。此外,还演示了如何使用自定义注解进行数据校验。
摘要由CSDN通过智能技术生成

1.java文件叫Annotation ,用@interface表示

2.原注解,@interface上面按需要注解上一些东西,包括@Retention,@Target,@Document,@Inherited四种

3.注解的保留策略:

@Retention(RetenttionPolicy.Source) //注解仅存在于源码中,在class字节码中不包含

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

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

4.注解的作用目标:

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

@Target(Element Type.FIELD)//字段枚举的常量

@Target(ElementType.METHOD)//方法

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

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

@Target(Element Type.LOCAL_VARIABLE) //局部变量

@Target(ElementType.ANNOTATION_TYPE) //注解

@Target(ElementType.PACKAGE) //包

5.注解包含在javadoc中

@Documented

6.注解可以被继承

@Inherited

7.注解解析器:用来自定义注解

package org.javaboy.vhr.explain;

import java.lang.annotation.*;

/**
 *
 * @author xushuai
 * @date 2021/12/1 1:35 下午
 * @param null
 * @return null
 */
@Documented
@Inherited
@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Init {
    public String value() default "123";
}
#建立user类
package org.javaboy.vhr.test;

import org.javaboy.vhr.explain.Init;
import org.javaboy.vhr.explain.Vadiate;

/**
 * @author xushuai
 * @date 2021年12月01日 1:38 下午
 */
public class User {
    @Vadiate(min = 1,max = 10)
    private String name;
    private String age;

    public String getName() {
        return name;
    }
   @Init(value = "xushuai")
    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }
  @Init(value = "123")
    public void setAge(String age) {
        this.age = age;
    }

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

    public static void main(String[] args) {
        User user = UserFactory.create();


        System.out.println(user.getName());
        System.out.println(user.getAge());
    }
}
package org.javaboy.vhr.test;

import org.javaboy.vhr.explain.Init;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author xushuai
 * @date 2021年12月01日 4:27 下午
 */
public class UserFactory {
    public static  User create() {
        User user = new User();
        //通过反射获取user类中的所有方法
        Method[] methods = User.class.getDeclaredMethods();
        try {
            for (Method method : methods) {
                //如果有注解就吧注解里的数据复制到user对象里
                if (method.isAnnotationPresent(Init.class)) {
                    Init annotation = method.getAnnotation(Init.class);
                    method.invoke(user, annotation.value());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
        return user;
    }
}

结果如下:

8.自定义注解进行校验:

package org.javaboy.vhr.test;
import org.javaboy.vhr.explain.Vadiate;


import java.lang.reflect.Field;

/**
 * @author xushuai
 * @date 2021年12月01日 5:09 下午
 */
public class UserCheck {
    public static boolean check(User user){
        if (user == null){
            System.out.println("!!!user对象不能为空");
            return false;
        }
        Field[] declaredFields = User.class.getDeclaredFields();

            if (declaredFields != null && declaredFields.length>0){
                for (Field declaredField : declaredFields) {
                    //如果有注解,就校验
                    if (declaredField.isAnnotationPresent(Vadiate.class)){
                        Vadiate annotation = declaredField.getAnnotation(Vadiate.class);
                        System.out.println(declaredField.getName()+"adasd");
                        if (declaredField.getName().equals("name")){
                            System.out.println(user.getName().length());
                        if(user.getName().length()> annotation.max()|| user.getName().length()<annotation.min()){
                            System.out.println("长度必须大于1小于10");
                            return false;
                        }
                    }
                }}}
        return true;
        }


    }


结果如下:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值