【问题标题】:IntelliJ plugin development getting actual object from PsiAnnotationMemberValueIntelliJ 插件开发从 PsiAnnotationMemberValue 获取实际对象
【发布时间】:2016-08-03 05:21:24
【问题描述】:

好的,所以在我正在开发的插件中,我需要获取传递给注解的参数值。我在#idea-users freenode 频道上得到了一个解决方案,我应该将 PsiAnnotationMemberValue 转换为 PsiLiteral,然后调用 getValue()。虽然这适用于原语和字符串之类的东西,但现在我正在尝试获取自定义枚举值。当我尝试这样做时,我的代码抛出了带有以下错误消息的 ClassCastException:

java.lang.ClassCastException: com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl cannot be cast to com.intellij.psi.PsiLiteral

代码:

@Override
public boolean eventIgnoresCancelled(PsiMethod method) {

    PsiLiteral literal = null;

    for (PsiAnnotation annotation : method.getModifierList().getAnnotations()) {
        if(annotation.getQualifiedName().contains("IsCancelled")) {
            literal = ((PsiLiteral) annotation.findAttributeValue("value"));
        }
    }

    if(literal == null || literal.getValue() == null) {
        return false;
    }
    Object tristateValue = literal.getValue();
    try {
        String name = (String) tristateValue.getClass().getMethod("name").invoke(tristateValue);
        return name.equalsIgnoreCase("TRUE") || name.equalsIgnoreCase("UNDEFINED");
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        e.printStackTrace();
    }
    return false;
}

【问题讨论】:

    标签: java intellij-idea intellij-plugin


    【解决方案1】:

    您的代码不应假定所有注释值都是文字,它们也可以是 .class 表达式、数组、其他注释等和引用。 IDEA 的 PSI 对您的枚举一无所知,但给定 PsiReferenceExpression 注释值,您可以检查其名称 (getReferenceName()) 甚至执行 resolve() 并获取也具有 getName() 方法的实际枚举常量。而且,从异常中可以看出,您已经拥有 PsiReferenceExpression 对象,所以请在 PsiLiteral 之外处理这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-19
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多