rspec/rules/S2109/java/rule.adoc

33 lines
1.3 KiB
Plaintext

== Why is this an issue?
The writer of an annotation can set one of three retention policies for it:
* ``++RetentionPolicy.SOURCE++`` - these annotations are dropped during compilation, E.G. ``++@Override++``, ``++@SuppressWarnings++``.
* ``++RetentionPolicy.CLASS++`` - these annotations are present in a compiled class but not loaded into the JVM at runtime. This is the default.
* ``++RetentionPolicy.RUNTIME++`` - these annotations are present in the class file and loaded into the JVM.
Only annotations that have been given a ``++RUNTIME++`` retention policy will be available to reflection. Testing for annotations with any other retention policy is simply an error, since the test will always return false.
This rule checks that reflection is not used to detect annotations that do not have ``++RUNTIME++`` retention.
=== Noncompliant code example
[source,java]
----
Method m = String.class.getMethod("getBytes", new Class[] {int.class,
int.class, byte[].class, int.class});
if (m.isAnnotationPresent(Override.class)) { // Noncompliant; test will always return false, even when @Override is present in the code
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
endif::env-github,rspecator-view[]