File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed
codeql-custom-queries-java/queries/likely-bugs Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
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()`"
Original file line number Diff line number Diff line change
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()`"
You can’t perform that action at this time.
0 commit comments