File: FormatStringAnnotation.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (42 lines) | stat: -rw-r--r-- 1,481 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Methods can be annotated with Error Prone's `@FormatMethod` annotation to
indicate that calls to this function should be treated similarly to
`String.format`: One of the parameters is a 'format string' (the first String
parameter or the only parameter annotated with `@FormatString`), and the
subsequent parameters are used as format arguments to that format string.

For example:

```java
@FormatMethod
void myLogMethod(@FormatString String fmt, Object... args) {}

// ERROR: 2nd format argument isn't a number
myLogMessage("My log message: %d and %d", 3, "has a message");
```

In order to avoid complex runtime issues when the format string part is
dynamically constructed, leading to a mismatch between the arguments and format
strings, we require that the 'format string' argument in calls to
`@FormatMethod`-annotated methods be one of:

*   Another `@FormatString`-annotated variable
*   A compile time constant string
*   A final or effectively final variable assigned to a compile time constant
    string
*   A string literal

We will then check that the format string and format arguments match.

For more information on possible format string errors, see the documentation on
the [FormatString check](FormatString).

The import for `@FormatMethod` is:

```java
import com.google.errorprone.annotations.FormatMethod;
```

## Suppression

Suppress false positives by adding the suppression annotation
@SuppressWarnings("FormatStringAnnotation") to the enclosing element.