假设我们有以下代码:
public class Demo {
@ABC(name = "abc")
private String field1;
@ABC
private String field2;
}
@interface ABC {
String name() default "";
}如何编写一个查询来选择没有@ABC属性的带注释的所有字段?
getValue(string)对象中有Annotation方法,但是getValue("name")为field2上的注释返回空字符串,因为它是默认值。但是,我想知道,我如何才能检查该财产是否存在,这是作者提到的。
发布于 2022-03-05 17:17:19
不幸的是,CodeQL没有为此提供任何谓词(请参见此相关问题)。但是,您可以利用一个事实,即默认值Expr似乎没有源中的位置(也就是说,它的getLocation()有一个.class文件位置)。
然后可以有一个实用程序谓词,如以下所示,以检测注释是否具有元素的默认值:
predicate hasDefaultValue(Annotation annotation, string elementName) {
// If value file location is not the same as annotation file location, then most likely it
// is the default value (unless there is a bug with the CodeQL extractor)
annotation.getValue(elementName).getLocation().getFile() != annotation.getLocation().getFile()
}但是请记住,这种行为并没有明确定义,而且将来可能会发生变化,或者CodeQL提取器的错误可能会在这里导致错误。此外,这对于出现在依赖项或JDK中的注释不起作用,因为注释本身也不存在于源中。
https://stackoverflow.com/questions/69232438
复制相似问题