自定义注解

1、定义注解:CherryAnnotation
2、注解逻辑:HelloServiceCgLib
3、使用注解

import java.lang.annotation.*;

//@CherryAnnotation被限定只能使用在类、接口或方法上面
@Documented
@Inherited
@Target(value = {ElementType.METHOD,ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface CherryAnnotation {
    String value() default "参数不能为空";

}

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class HelloServiceCgLib implements MethodInterceptor {
    private Class target;

    public Object getInstance(Class target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object object, Method method, Object[] objects, MethodProxy proxy) throws Throwable {
//        System.out.println("我是CGLIB的动态代理");
//        System.out.println("我准备执行了");
        if (!check(method,objects)) {
//            System.out.println("我没能成功执行");
            return false;
        }
        Object returnObj = proxy.invokeSuper(object, objects);
//        System.out.println("我已经正确执行过了");
        return returnObj;
    }

    /**
     * 对参数校验的方法
     * @param method 目标方法
     * @param objects 相关参数值
     * @return
     */
    public  boolean check(Method method,Object[] objects)  {
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i <parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.isAnnotationPresent(CherryAnnotation.class)) {
                CherryAnnotation annotation = parameter.getAnnotation(CherryAnnotation.class);
                if (objects==null ||objects[i]==null) {
                    System.out.println(parameter.getName()+annotation.value());
                    return false;
                }else if(objects[i]=="zs"){
                    System.out.println(parameter.getName()+"不可以是张三");
                    return false;
                }

            }
        }
        return true;
    }
}


public class use_zhujie {

    public void say(@CherryAnnotation String name, @CherryAnnotation String pass){
        System.out.println("ok");
    }
}

  

posted @ 2019-06-21 00:32  黑魔法os  阅读(207)  评论(0编辑  收藏  举报