Java自定义注解实现过程

本文介绍了一种使用自定义注解进行参数校验的方法,包括注解的创建、解析及校验流程,并通过示例展示了如何在Java项目中应用自定义注解。

步骤
1、创建自定义注解类,并添加校验规则
2、解析自定义注解类并实现校验方法
3、创建测试类并声明自定义注解
4、编写Junit测试类测试结果

自定义注解类

package com.swk.common.annotation;

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

/**
 * 自定义注解类
 * @author fuyuwei
 * @Retention: 定义注解的保留策略
 * @Retention(RetentionPolicy.SOURCE)  注解仅存在于源码中,在class字节码文件中不包含
   @Retention(RetentionPolicy.CLASS)   默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
   @Retention(RetentionPolicy.RUNTIME) 注解会在class字节码文件中存在,在运行时可以通过反射获取到

   @Target 注释类型声明
   CONSTRUCTOR 构造方法声明
   FIELD 字段声明(包括枚举常量)
   LOCAL_VARIABLE 局部变量声明
   METHOD 方法声明
   PACKAGE 包声明
   PARAMETER 参数声明
   TYPE 类、接口(包括注释类型)或枚举声明
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER})
public @interface CustomAnnotation {

    /**
     * 是否为空
     * @return
     */
    boolean isNull() default false;

    /**
     * 最大长度
     * @return
     */
    int maxLength() default 8;

    /**
     * 字段描述
     * @return
     */
    String description() default "";

}

实现自定义注解类规则读取与校验

package com.swk.common.annotation;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.util.StringUtils;

import com.swk.common.enums.CommonPostCode;
import com.swk.common.exception.PostingException;


/**
 * 解析自定义注解,并完成校验
 * @author fuyuwei
 */
public class AnnotationChecker {

    private final static ConcurrentHashMap<String,Field[]> fieldsMap = new ConcurrentHashMap<String, Field[]>();

    public AnnotationChecker(){
        super();
    }

    public static void checkParam(Object object) throws PostingException{
        Class<? extends Object> clazz = object.getClass();
        Field[] fields = null;
        if(fieldsMap.containsKey(clazz.getName())){
            fields = fieldsMap.get(clazz.getName());
        }
        // getFields:获得某个类的所有的公共(public)的字段,包括父类;getDeclaredFields获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段
        else{
            fields = clazz.getDeclaredFields();
            fieldsMap.put(clazz.getName(), fields);
        }
        for(Field field:fields){
            synchronized(field){
                field.setAccessible(true);
                check(field, object);
                field.setAccessible(false);
            }
        }
    }

    private static void check(Field field,Object object) throws PostingException{
        String description;
        Object value = null;
        CustomAnnotation ca = field.getAnnotation(CustomAnnotation.class);
        try {
            value = field.get(object);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (ca == null) return;
        // 如果没有标注description默认展示字段名称
        description = ca.description().equals("")?field.getName():ca.description();
        if(!ca.isNull()){
            if(value == null || StringUtils.isEmpty(value.toString().trim())){
                throw new PostingException(CommonPostCode.PARAM_LENGTH.getErrorCode(),description+" "+CommonPostCode.PARAM_NULL.getErrorMesage());
            }
        }
        if(value.toString().length() > ca.maxLength()){
            throw new PostingException(CommonPostCode.PARAM_LENGTH.getErrorCode(),description+" "+CommonPostCode.PARAM_LENGTH.getErrorCode());
        }
    }
}

创建依赖的其他类

枚举类

package com.swk.common.enums;

public enum CommonPostCode {

    PARAM_NULL(-1,"param required"),
    PARAM_LENGTH(-2,"param too long");

    private int errorCode;

    private String errorMesage;


    private CommonPostCode(int errorCode, String errorMesage) {
        this.errorCode = errorCode;
        this.errorMesage = errorMesage;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMesage() {
        return errorMesage;
    }

    public void setErrorMesage(String errorMesage) {
        this.errorMesage = errorMesage;
    }


}

自定义异常类

package com.swk.common.exception;

public class PostingException extends RuntimeException {

    private static final long serialVersionUID = 5969404579580331293L;

    private int errorCode;

    private String errorMessage;

    public PostingException(int errorCode, String errorMessage) {
        super();
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }



}

创建声明自定义注解的测试类

package com.swk.request;

import com.swk.common.annotation.CustomAnnotation;

public class UserInfoRequest {

    @CustomAnnotation(isNull=false,maxLength=4,description="姓名")
    private String name;

    @CustomAnnotation(isNull=false,maxLength=11,description="手机号")
    private String mobile;

    public String getName() {
        return name;
    }

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

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }


}

编写Junit测试类

package com.swk.test.annotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.sun.istack.internal.logging.Logger;
import com.swk.common.annotation.AnnotationChecker;
import com.swk.common.exception.PostingException;
import com.swk.request.UserInfoRequest;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class AnnotationTest {

    private Logger logger = Logger.getLogger(AnnotationTest.class);

    @Test
    public void testAnnotation(){
        UserInfoRequest request = new UserInfoRequest();
        try {
            AnnotationChecker.checkParam(request);
        } catch (PostingException e) {
            logger.info(e.getErrorCode()+":"+e.getErrorMessage());
        }
    }
}

运行结果
这里写图片描述

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class AnnotationTest {

    private Logger logger = Logger.getLogger(AnnotationTest.class);

    @Test
    public void testAnnotation(){
        UserInfoRequest request = new UserInfoRequest();
        request.setName("齐天大圣孙悟空");
        try {
            AnnotationChecker.checkParam(request);
        } catch (PostingException e) {
            logger.info(e.getErrorCode()+":"+e.getErrorMessage());
        }
    }
}

运行结果
这里写图片描述

### Java 自定义注解实现方法与示例 #### 创建自定义注解Java 中,可以通过 `@interface` 关键字来声明一个新的注解。以下是创建自定义注解的关键要素: 1. **定义注解名称** 使用 `@interface` 定义新的注解类型。 2. **设置属性(可选)** 可以为注解添加属性,这些属性类似于方法签名,但不带具体实现。 3. **指定目标和保留策略** 需要通过元注解 `@Target` 和 `@Retention` 来限定注解的作用范围以及生命周期。 下面是一个简单的自定义注解示例[^4]: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; // 设置注解作用的目标为方法 @Target(ElementType.METHOD) // 设置注解的保留策略为运行时可见 @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value() default ""; // 默认值为空字符串 int count() default 0; // 默认计数值为0 } ``` --- #### 使用自定义注解 一旦定义好注解,就可以将其应用到类、方法或其他允许的地方。以下是如何使用上述 `@MyAnnotation` 的例子[^1]: ```java class MyClass { @MyAnnotation(value = "This is a sample method", count = 5) public void myMethod() { System.out.println("Method executed"); } } ``` 在这里,`myMethod()` 被标记了一个带有参数的 `@MyAnnotation` 注解。 --- #### 获取注解并读取其值 为了利用注解中的信息,通常会结合反射机制动态解析它们。以下是从类中提取注解信息的一个完整示例[^2]: ```java import java.lang.reflect.Method; public class AnnotationMain { public static void main(String[] args) throws Exception { MyClass obj = new MyClass(); // 获取当前对象的Class实例 Class<?> cls = obj.getClass(); // 查找所有的Declared Methods Method[] methods = cls.getDeclaredMethods(); for (Method method : methods) { // 判断该方法是否有特定注解 if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); // 输出注解中的value和count字段 String value = annotation.value(); int count = annotation.count(); System.out.println("Value: " + value + ", Count: " + count); } } } } ``` 当执行此代码时,它将打印出如下内容: ``` Value: This is a sample method, Count: 5 ``` --- #### 总结 以上展示了完整的流程:从定义自定义注解到实际运用再到通过反射获取其中的信息。这种技术非常适用于框架设计或自动化处理场景下,能够显著减少重复劳动并提升灵活性[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值