gpt4 book ai didi

java - 格式化方法 : how to forward their arguments to another format method?

转载 作者:行者123 更新时间:2023-12-02 12:16:40 25 4
gpt4 key购买 nike

我不明白为什么会收到与 @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 中的示例非常相似:

Your project may contain methods that forward their arguments to a format method. Consider for example the following log method:

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

You should annotate such a method with the @FormatMethod annotation. This instructs the Format String Checker to check every invocation of the method. This check is analogous to the check done on every invocation of built-in format methods like String.format.

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

  • 不要忘记将选择类型系统:更改为格式字符串检查器
  • 请记住,在线工具使用旧版本的 Checker Framework (2.1.10 @ 08.09.2017)

最佳答案

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

manual@FormatMethod documentation@FormatMethod 导致对带注释的方法的调用进行检查,但它们不对带注释的方法内的调用做出任何 promise 。

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

关于java - 格式化方法 : how to forward their arguments to another format method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46118099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com