与注解相关的类

Annotable,可以被附上注解的元素
Annotation,一个注解,例如@Override
AnnotationType,Java的注解类型,例如java.lang.Override
AnnotationElement

代码示例

WebGoat v8.0.0

  1. import java
  2. from Annotation anno, AnnotationType annotp
  3. where anno.getFile().toString() = "StartLesson" and
  4. anno.getType() = annotp
  5. select annotp.getQualifiedName(), anno, anno.getValue("path")

匹配结果示例

annotp.getQualifiedName() anno anno.getValue(“path”)
org.springframework.web.bind.annotation.RequestMapping @RequestMapping(path=….) startlesson.mvc

image.png

查找缺失@Override标注的方法

查看被覆盖了,但是缺少@Override标注的方法
代码示例

  1. import java
  2. class OverrideAnnotation extends Annotation {
  3. OverrideAnnotation() {
  4. this.getType().hasQualifiedName("java.lang", "Override")
  5. }
  6. }
  7. from Method overriding, Method overridden
  8. where overriding.overrides(overridden) and
  9. not overriding.getAnAnnotation() instanceof OverrideAnnotation
  10. select overriding, "Method overrides another method, but does not have an @Override annotation."

查找调用了已废弃的方法

查找方法A,方法A调用了方法B,方法B被@Deprecated标注了
代码示例

  1. import java
  2. class DeprecatedAnnotation extends Annotation {
  3. DeprecatedAnnotation() {
  4. this.getType().hasQualifiedName("java.lang", "Deprecated")
  5. }
  6. }
  7. from Call call
  8. where call.getCallee() instanceof DeprecatedMethod
  9. and not call.getCaller() instanceof DeprecatedMethod
  10. select call, "This call invokes a deprecated method."

改进

除了@Deprecated以外,Java库提供了另一个注解来标注某个方法已经废弃了。
可以使用@SuppressWarnings(“deprecated”)来标注某个方法已经被废弃了

  1. @SuppressWarnings("deprecated")
  2. void r() {
  3. m();
  4. }

代码改进示例
使用了强制类型转换+正则表达式匹配文本

  1. class SuppressDeprecationWarningAnnotation extends Annotation{
  2. SuppressDeprecationWarningAnnotation(){
  3. this.getType().hasQualifiedName("java.lang", "SuppressWarnings") and
  4. this.getAValue().(StringLiteral).getLiteral().regexpMatch(".*deprecation.*");
  5. }
  6. }
  1. import java
  2. // Insert the class definitions from above
  3. from Call call
  4. where call.getCallee() instanceof DeprecatedMethod
  5. and not call.getCaller() instanceof DeprecatedMethod
  6. and not call.getCaller().getAnAnnotation() instanceof SuppressDeprecationWarningAnnotation
  7. select call, "This call invokes a deprecated method."