![](/img/trans.png)
[英]Java/Kotlin annotation processor: get type of annotated field/property
[英]How to get return type of annotated method in annotation processor?
我正在學習編寫自定義注釋。 我有一個簡單的注釋,需要驗證方法的返回類型是否與注釋中指定的返回類型匹配。 下面是代碼。
注釋代碼:
@Target(ElementType.METHOD)
public @interface ReturnCheck {
String value() default "void";
}
注釋處理器:
@SupportedAnnotationTypes("com.rajesh.customannotations.ReturnCheck")
public class ReturnCheckProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for ( Element element : roundEnv.getElementsAnnotatedWith(ReturnCheck.class) ) {
//Get return type of the method
}
return false;
}
}
我想獲取帶注釋的方法的返回類型,以便可以將其與注釋中指定的值進行比較。
如何獲得方法的返回類型?
這是您需要的:
if (element.getKind() == ElementKind.METHOD) {
TypeMirror returnType = ((ExecutableElement) element).getReturnType();
// use returnType for stuff ...
}
說明:
您可以檢查ElementKind
以便分派其具體類型。 建議使用此方法代替instanceof
。 之后,您知道它的ExecutableElement
並將其ExecutableElement
為一個。
有關更多詳細信息,請參見ExecutableElement和Element 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.