[英]Can I get the value of an annotated parameter of a method call?
我想獲取方法調用中使用的帶注釋參數的值:
public class Launch {
public static void main(String[] args) {
System.out.println("hello");
testAnn(15);
}
private static void testAnn(@IntRange(minValue = 1,maxValue = 10)int babyAge) {
System.out.println("babyAge is :"+babyAge);
}
}
我正在嘗試創建一個自定義注釋來驗證 integer 值范圍,該注釋采用min
和max
,因此如果有人使用此范圍之外的 integer 值調用此 function,則會出現一條消息錯誤,並提供一些提示出錯了。
我在 Java 注釋過程中工作以獲取值並將其與@IntRange
中包含的max/min
進行比較
這就是我得到的:
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for(TypeElement annotaion: annotations) {
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(IntRange.class);
for (Element element : annotatedElements) {
Executable methodElement= (Executable) element.asType();
ExecutableType methodExcutableType = (ExecutableType) element.asType();
String elementParamClassName = methodElement.getParameterTypes()[0].getCanonicalName();
if(!elementParamClassName.equals(PARAM_TYPE_NAME)) {
messager.printMessage(Diagnostic.Kind.ERROR,"Parameter type should be int not "+elementParamClassName);
}else {
IntRange rangeAnno = element.getAnnotation(IntRange.class);
int maxValue = rangeAnno.maxValue();
int minValue = rangeAnno.minValue();
//code to retrive argument passed to the function with
//annotated parameter (@IntRange(..))
}
}
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.