注解介绍
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- 参数空值处理注解
- 1、从第一个对象开始
- 2、给定的参数为顺序判断数量-1
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ParamJudgement {
int value() default 0;
}
切面类
import annotation.ParamJudgement;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
/***
- 功能:处理方法参数空值判断处理
- 优化空间较大
*/
@Component
@Aspect
public class ParamJudgementAspect {
@Around("@annotation(paramJudgement)")
public Object around(ProceedingJoinPoint joinPoint, ParamJudgement paramJudgement){
Object obj = null;
Object[] args = joinPoint.getArgs();
int value = paramJudgement.value();
String name = joinPoint.getSignature().getName();
for (int i=0;i<=value;i++){
Object param = args[i];
if (param == null){
throw new IllegalArgumentException(name + "的参数异常,不合法!");
}
}
try {
obj = joinPoint.proceed();
} catch (Throwable throwable) {
//throwable.printStackTrace();
throw new RuntimeException(throwable);
}
return obj;
}
}
使用示例
注意:在spring项目中使用。