如何检查注释处理器中的方法参数类型?

tow*_*owi 5 java reflection annotation-processing

使用纯反射,这很容易,但注释处理器世界似乎有所不同。我如何从TypeMirror返回者getParameterTypes()转到String.class

在我的注释处理器中,我想检查当前访问的方法是否具有完全相同的形式:

public boolean someName(String input)
Run Code Online (Sandbox Code Playgroud)

我可以检查原始返回类型,但String参数会出现问题:

private void processAnnotation(Element method, Messager msg) {
    final MyAnnotation ann = method.getAnnotation(MyAnnotation.class);
    if (method.getKind() != ElementKind.METHOD) {
      error("annotation only for methods", method);
    }
    Set<Modifier> modifiers = method.getModifiers();
    if(!modifiers.contains(Modifier.PUBLIC)) {
      error("annotated Element must be public", method);
    }
    if(modifiers.contains(Modifier.STATIC)) {
      error("annotated Element must not be static", method);
    }
    ExecutableType emeth = (ExecutableType)method.asType();
    if(!emeth.getReturnType().getKind().equals(TypeKind.BOOLEAN)) {
      error("annotated Element must have return type boolean", method);
    }
    if(emeth.getParameterTypes().size() != 1) {
      error("annotated Element must have exactly one parameter", method);
    } else {
      TypeMirror param0 = emeth.getParameterTypes().get(0);
      // TODO: check if param.get(0) is String
    }
}
Run Code Online (Sandbox Code Playgroud)

Rad*_*def 6

我们可以Elements.getTypeElement在处理过程中通过规范名称来检索类型。

Types    types = processingEnv.getTypeUtils();
Elements elems = processingEnv.getElementUtils();

TypeMirror param0 = m.getParameterTypes.get(0);
TypeMirror string = elems.getTypeElement("java.lang.String").asType();

boolean isSame = types.isSameType(param0, string);
Run Code Online (Sandbox Code Playgroud)

没有办法获得这样的“类”,因为注释处理在部分编译上运行,我们无法加载正在编译的类。