CodeQL 文档

AnnotationPresent 检查

ID: java/ineffective-annotation-present-check
Kind: problem
Security severity: 
Severity: error
Precision: medium
Tags:
   - correctness
   - logic
Query suites:
   - java-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

为了能够在运行时对 AnnotatedElement 使用 isAnnotationPresent 方法,必须使用 RUNTIME 保留策略显式注释注释。否则,注释在运行时不会被保留,并且不能使用反射来观察。

建议

如果您希望在运行时使用 AnnotatedElement.isAnnotationPresent 观察注解的存在,请使用 RUNTIME 保留策略显式注解注解。

示例

在以下示例中,对 isAnnotationPresent 的调用返回 false,因为无法使用反射观察到该注解。

public class AnnotationPresentCheck {
	public static @interface UntrustedData { }

	@UntrustedData
	public static String getUserData() {
		Scanner scanner = new Scanner(System.in);
		return scanner.nextLine();
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		String data = getUserData();
		Method m = AnnotationPresentCheck.class.getMethod("getUserData");
		if(m.isAnnotationPresent(UntrustedData.class)) {  // Returns 'false'
			System.out.println("Not trusting data from user.");
		}
	}
}

为了纠正这个问题,注解使用 RUNTIME 保留策略进行注解。

public class AnnotationPresentCheckFix {
	@Retention(RetentionPolicy.RUNTIME)  // Annotate the annotation
	public static @interface UntrustedData { }

	@UntrustedData
	public static String getUserData() {
		Scanner scanner = new Scanner(System.in);
		return scanner.nextLine();
	}

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		String data = getUserData();
		Method m = AnnotationPresentCheckFix.class.getMethod("getUserData");
		if(m.isAnnotationPresent(UntrustedData.class)) {  // Returns 'true'
			System.out.println("Not trusting data from user.");
		}
	}
}

参考资料

  • ©GitHub 公司
  • 条款
  • 隐私