将动态值传递给Java批注

时间:2018-08-24 19:02:18

标签: java spring annotations aop

请考虑以下情形:

public void someMethod(){ }

我想用自定义注释@CustomAnnotation注释someMethod()。我想将动态参数从方法参数中带入CustomAnnotation中,并在方法签名中未声明该参数的情况下引发编译时错误。

例如:

@CustomAnnotation(mandatorySample = "customId")
public void someMethod(String customId) {
}

对于上述代码段,如果someMethod没有传递“ customId”参数,我想抛出编译时错误。 主要目标是从方法参数中获取动态id参数,或为方法和注释使用单个参数。

我的研究: 我研究的一种解决方案是通过参数位置使用注入,并从反射中获取值。但是,我仍然无法在其中引发编译时错误。

我愿意接受基于#Java或#Spring的解决方案。

*更多说明:
可以说我的注释是

Public @interface Logger { 
  String mandatoryLogParam(); 
} 


让方法someLogMethod(...)使用我的注释。考虑以下情况。

** Invalid Usage ** 
@Logger(mandatoryLogParam = ‘myMandatoryGeneratedId’)
public void someLogMethod(String logMessage) {
}
MyExpectation: To throw compile error as
-> Method signature should includeparameter named “myMandatoryGeneratedId”

** Valid Usage: **
@Logger(mandatoryLogParam = ‘myMandatoryGeneratedId’)
public void someLogMethod(String logMessage, String myMandatoryGeneratedId) {
}
MyExpectation: No compile error is thrown. 

我的目标是使用该方法定义的参数作为我的内部注释逻辑。同时使用注释为开发人员引入编译时间检查。

观察以上代码中的 *'myMandatoryGeneratedId'* 用法。

这可能吗?还有其他解决方法吗?

0 个答案:

没有答案