我正在尝试实现自定义lint检查,如果函数参数类型没有使用特定注释进行注释,则应该报告对给定函数的调用。
@MyAnnotation
class ClassA {
void memberMethod() {
SomeUtil.someMethod(this); // first call
}
}
class ClassB {
void memberMethod() {
SomeUtil.someMethod(this); // second call
}
}
我希望lint报告第二个电话,但不是第一个电话。
我设法报告了参数表达式。但lint报告了两个电话,我不知道为什么......
public class MyDetector extends Detector implements Detector.JavaPsiScanner {
private static final Class<? extends Detector> DETECTOR_CLASS = MyDetector.class;
private static final EnumSet<Scope> DETECTOR_SCOPE = Scope.JAVA_FILE_SCOPE;
private static final Implementation IMPLEMENTATION = new Implementation(
DETECTOR_CLASS,
DETECTOR_SCOPE
);
private static final String ISSUE_ID = "MyId";
private static final String ISSUE_DESCRIPTION = "Some short description.";
private static final String ISSUE_EXPLANATION = "Some long description.";
private static final Category ISSUE_CATEGORY = Category.CORRECTNESS;
private static final int ISSUE_PRIORITY = 7;
private static final Severity ISSUE_SEVERITY = Severity.WARNING;
public static final Issue ISSUE = Issue.create(
ISSUE_ID,
ISSUE_DESCRIPTION,
ISSUE_EXPLANATION,
ISSUE_CATEGORY,
ISSUE_PRIORITY,
ISSUE_SEVERITY,
IMPLEMENTATION
);
public MyDetector() {
}
@Override
public boolean appliesTo(Context context, File file) {
return true;
}
@Override
public EnumSet<Scope> getApplicableFiles() {
return Scope.JAVA_FILE_SCOPE;
}
@Override
public List<String> getApplicableMethodNames() {
return Collections.singletonList("someMethod");
}
@Override
public void visitMethod(JavaContext context, JavaElementVisitor visitor, PsiMethodCallExpression call, PsiMethod method) {
for (PsiExpression psi : call.getArgumentList().getExpressions()) {
PsiType type = psi.getType();
if (type != null) {
for (PsiAnnotation anno : type.getAnnotations()) { // type.getAnnotations() is always empty
if (MyAnnotation.class.getName().equals(anno.getQualifiedName())) {
return;
}
}
context.report(ISSUE, context.getLocation(psi), ISSUE.getBriefDescription(TextFormat.TEXT));
}
}
}
}
也许我在这里做错了但是我找不到一些好的Psi文档......
答案 0 :(得分:0)
经过深入研究后,我终于开始工作了。 我不得不将PsiType转换为PsiClass并从那里读取注释。