FormatMethod:如何将他们的参数转发给另一种格式方法?

时间:2017-09-08 13:51:39

标签: java checker-framework

我不明白为什么会收到与@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

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

  

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

@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)

1 个答案:

答案 0 :(得分:1)

@FormatMethod注释按照文档记录,但不是您想要的 - 并且您的解释是合理的。

manual@FormatMethod documentation表示@FormatMethod会导致对带注释的方法的调用进行检查,但是他们没有对带注释的方法中的调用做出任何承诺。

但是,此bug最近才fixed。您可以build the Checker Framework from source或等待下一个版本。