如何检查方法的 TypeMirror 返回类型是否为枚举类型

huangapple go评论55阅读模式
英文:

How to check if a TypeMirror returnType of a method is an enum

问题

我正在编写一个注解处理器。我的注解适用于接口内的方法:

public interface Sample {
   @MyAnnotation
   public ReturnEnum method();
}

ReturnEnum 是我自己编写的枚举类型。
在我的处理器代码中,我做了类似这样的操作:

TypeMirror returnType = methodElement.getReturnType();

我可以获取到返回类型的名称:my.package.ReturnEnum
但我不知道是否可以检查它是否是枚举类型。
有方法可以吗?

问候。

英文:

I am writing a annotation processor. My annotation is applied to methods inside an interface:

public interface Sample {
   @MyAnnotation
   public ReturnEnum method();
}

ReturnEnum is a enum written by myself.
In my processor code I do something like this:

TypeMirror returnType = methodElement.getReturnType();

I can get the name of my return type: my.package.ReturnEnum
But I don't know, if I can check it is a enum type.
Is there a way?

greetings.

答案1

得分: 4

好的。找一个解决方案。似乎你只需要将它强制转换为特定的TypeElement类型。

public void myMethod(ExecutableElement methodElement) {
   TypeMirror typeMirror = methodElement.getReturnType();
   if (typeMirror.getKind() == TypeKind.DECLARED) {
      TypeElement typeElement = (TypeElement) ((DeclaredType) typeMirror).asElement();
      if (typeElement.getKind() == ElementKind.ENUM) {
         // 我想要在这里执行...
      }
   }
}
英文:

Ok. Find a solution. Seems like you just have to cast it to a specific TypeElement.

public void myMethod(ExecutableElement methodElement) {
   TypeMirror typeMirror = methodElement.getReturnType();
   if (typeMirror.getKind() == TypeKind.DECLARED) {
      TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement();
      if (typeElement.getKind() == ElementKind.ENUM) {
         // I wanted to get here...
      }
   }
}

答案2

得分: -2

我不确定我理解你的问题。

但你可以使用if语句,甚至是更好的switch语句来比较值。

英文:

I am not sure I understand your question.

But you can use if statements or even better switch statements to compare values.

huangapple
  • 本文由 发表于 2020年10月9日 13:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64274580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定