java自定义注解调用注解方法

ar7v8xwq  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(468)

我有两个注解(@translation,@translate)。

@Retention(RUNTIME)
@Target({FIELD})
public @interface Translation {
}

@Retention(RUNTIME)
@Target({PARAMETER})
public @interface Translate {
}

我想用@translation标记一些如下字段

class User {
   @Translation
   String name;
}

我有一个实现@translation的类。

>   public class Injector {
    public void inject(Object instance) {
        Class clazz = instance.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Translation.class)) {
                Translation set = field.getAnnotation(Translation.class);
                // set value to fields
            }
        }
    }
}

我想用@translate like执行方法inject

class UserDto{

String name;

void UserDto(@Translate User user){
    name = user.name;
}

如果我问错了,请纠正我。谢谢你的建议。

vsdwdz23

vsdwdz231#

据我所知,您需要使用面向方面编程(aspect-oriented programming,springaop)在方法调用和验证用@translate注解的参数之前采取一些操作。
另一方面,您可以实现方法,该方法验证@translate注解,就像您对@translate所做的那样,并在构造函数中调用它。

qlzsbp2j

qlzsbp2j2#

first-off-spring aop(基于代理)只用于拦截方法调用。每当在方法上遇到注解时,就会触发以下方面(在您的情况下,可以使用setters)。尤其 @Around 在特定方法的入口和存在时执行。它应该或多或少类似于以下内容。我用过的笔记 List 用于捕获方法参数的字符串。

@Aspect
@Component
public class TranslateAspect {

    Logger logger = LoggerFactory.getLogger(TranslateAspect.class);

    //The argument ProceedingJoinPoint will be an executing**method**which has been annotated with @Translation. 
    @Around("@annotation(your.package.Translation)")
    public Object translationInterceptor(ProceedingJoinPoint jointPoint) throws Throwable {
        List<String> arguments = new ArrayList<>(); //may be add a map
        String declaringMethod = TranslateAspect.class.getSimpleName();
        Object proceed = null;
        try{
            MethodSignature methodSignature = (MethodSignature) jointPoint.getSignature();
            Method method = methodSignature.getMethod();
            declaringMethod = methodSignature.getDeclaringType().getSimpleName() + "." + method.getName() + "()"; //like clazz.methodName()

            //argument name and value
            String[] argumentNames = methodSignature.getParameterNames();
            Object[] methodArguments = jointPoint.getArgs();

            //add name and value of each parameter
            for(int i=0; i < methodArguments.length; i++){
                arguments.add(argumentNames[i] + " = " + methodArguments[i]);
            }

            proceed = jointPoint.proceed();
        }catch (Exception e) {
            throw e; //should not swallow the thrown exception
        }finally {
            // add logging?
        }
        return proceed;
    }
}

相关问题