java - 注释处理器: how to verity method return type is Map<Foo,栏>

标签 java return-type annotation-processing

如何验证方法的返回类型是带有类型参数 Foo 和 Bar 的 Map?

public Map<Foo, Bar> getValue();

public void verify(ExecutableElement method) {
     TypeMirror returnType = method.getReturnType();
     // how to verify return type is Map<Foo,Bar>

} 

Foo 和 Bar 可以是原始类型、用户定义类型或 java 类型(在 java.* 和 javax.* 包中)。这个问题实际上是:如何检查TypeMirror是Map<Foo,Bar> .

最佳答案

不确定是否有更简单的方法,但以下方法有效。

public void verify(ExecutableElement method) {

    DeclaredType declaredMethod = (DeclaredType) method;
    Elements elementUtils = processingEnv.getElementUtils();

    TypeMirror mapType = elementUtils.getTypeElement("java.util.Map").asType();
    TypeMirror typeArg1 = elementUtils.getTypeElement("path.to.Foo").asType();
    TypeMirror typeArg2 = elementUtils.getTypeElement("path.to.Bar").asType();

    boolean equalMainType = declaredMethod.asElement().asType().equals(mapType);
    Iterator<? extends TypeMirror> iterator = declaredMethod.getTypeArguments().iterator();
    boolean typeArgRes1 = iterator.next().equals(typeArg1);
    boolean typeArgRes2 = iterator.next().equals(typeArg2);

    if (equalMainType && typeArgRes1 && typeArgRes2) {
        // Type matches
    }
}

关于java - 注释处理器: how to verity method return type is Map<Foo,栏>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48307826/

相关文章:

java - EclipseLink DDL 生成错误

c++ - 直接从 C++0x lambda 调用方返回

c++ - 为什么 C++ 中的 main() 函数不采用除 int 和 void 以外的任何其他返回类型

java - 为什么 Velocity "Velocity is not initialized correctly."会出现此错误?

java - 将自定义注释处理器与 Checker Framework 一起使用

java - 在注释处理期间如何从方法获取其参数的注释?

java - 确定用户感知字符数的正确算法是什么?

java - 如何防止XML中的自关闭<tags/>?

Java aes key 到 32 字节字符串表示

function - 有没有办法让函数根据输入返回整数或字符串?