Skip to content

Commit 2eb2dd3

Browse files
committed
Add queries for getClass() calls on annotations and enums
1 parent 44fe494 commit 2eb2dd3

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Finds calls to `getClass()` on annotation objects. The result will not be the annotation interface
3+
* type but instead some internal implementation class which implements that interface. Therefore instead
4+
* [`Annotation#annotationType()`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/annotation/Annotation.html#annotationType())
5+
* should be used which returns the annotation interface type, or maybe the code can be simplified
6+
* using `instanceof`, for example `annotation instanceof MyAnnotation`.
7+
*
8+
* See also [this Stack Overflow question](https://stackoverflow.com/q/36293911) about
9+
* the purpose of the `annotationType` method.
10+
*
11+
* @kind problem
12+
* @id TODO
13+
*/
14+
15+
import java
16+
17+
from MethodAccess getClassCall
18+
where
19+
getClassCall.getMethod().hasStringSignature("getClass()") and
20+
getClassCall.getReceiverType() instanceof AnnotationType
21+
select getClassCall, "Instead of `getClass()` should prefer `annotationType()`"
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Finds calls to `getClass()` on enum values. If an enum constant implements or overrides methods,
3+
* it is created as anonymous class. In this case `getClass()` will return that anonymous class,
4+
* which is often undesired. Instead
5+
* [`Enum#getDeclaringClass()`](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Enum.html#getDeclaringClass())
6+
* should be used.
7+
*
8+
* @kind problem
9+
* @id TODO
10+
*/
11+
12+
import java
13+
14+
from MethodAccess getClassCall
15+
where
16+
getClassCall.getMethod().hasStringSignature("getClass()") and
17+
getClassCall.getQualifier().getType() instanceof EnumType and
18+
// Ignore own method access, then it is either intentional or at least risk of incorrect behavior
19+
// is reduced since implementation of enum is in the same file
20+
not getClassCall.isOwnMethodAccess()
21+
select getClassCall, "Instead of `getClass()` should prefer `getDeclaringClass()`"

0 commit comments

Comments
 (0)