0

我不明白为什么我会收到与@FormatMethod.

这是一个非常简单的示例,但失败了:

import org.checkerframework.checker.formatter.qual.FormatMethod;
import java.util.Locale;

public class FormatExample {

    public void example() {
        String ex1 = String.format(Locale.ENGLISH, "%s %d", "cost", 12);
        log("%d", 0);
    }

    @FormatMethod
    static void log(String format, Object... args) {
        String ex1 = String.format(Locale.ENGLISH, format, args);
        // The line above causes the error (see below)
    }
}

它失败并显示以下错误消息:

FormatExample.java:13: error: 
    [format.string.invalid] invalid format string (is a @Format annotation missing?)
                String ex1 = String.format(Locale.ENGLISH, format, args);

我错过了什么?
我正在使用版本:javac 1.8.0-jsr308-2.1.14

我尝试做的与文档中的示例非常相似: 10.5 @FormatMethod

您的项目可能包含将其参数转发给格式方法的方法。例如,考虑以下日志方法:

@FormatMethod
void log(String format, Object... args) {
    if (enabled) {
        logfile.print(indent_str);
        logfile.printf(format , args);
    }
}

您应该使用 @FormatMethod 注释来注释这样的方法。这指示格式字符串检查器检查方法的每次调用。此检查类似于对内置格式方法(如 String.format)的每次调用所做的检查。

提示:您可以在Checker Framework Live Demo
中轻松重现该问题。

  • 不要忘记更改Choose a type system:Format String Checker
  • 请记住,在线工具使用的是旧版本的 Checker Framework ( 2.1.10@ 08.09.2017)
4

1 回答 1

1

注释按记录工作,@FormatMethod但不是您想要的 - 您的解释是合理的。

手册@FormatMethod文档说这@FormatMethod会导致检查对带注释的方法的调用,但它们没有对带注释的方法内的调用做出任何承诺。

然而,这个错误最近已被修复。您可以从源代码构建 Checker Framework或等待下一个版本。

于 2017-09-09T00:23:56.770 回答