简体   繁体   English

如何在编译时验证变量 Arguments (Varargs) 的长度?

[英]How to validate the length of Variable Arguments (Varargs) at compile time?

I want to write a function to do replacing in string template with varargs, for example:我想写一个 function 用可变参数替换字符串模板,例如:

public static String replace (String original, String... replacements) {
    for (int i = 0; i < replacements.length; i += 2) {
        original = original.replace(replacements[i], replacements[i + 1];
    }
}

so I can call this function like:所以我可以这样称呼这个 function :

String replaces = replace("NAME TIME", "NAME", "Abc", "TIME", "20:12");

Apparently, replacements.length should be a multiple of 2 and I want to validate this at compile time, I want to achieve something like:显然, replacements.length应该是2的倍数,我想在编译时验证这一点,我想实现类似:

@ValidateVarargs("length % 2 == 0", "replacements.length must be a multiple of 2")
public static String replace (String original, String... replacements) {
    for (int i = 0; i < replacements.length; i += 2) {
        original = original.replace(replacements[i], replacements[i + 1];
    }
}

And when I call this function with odd number of replacement strings, It will give me some compilation errors like:当我用奇数个替换字符串调用这个 function 时,它会给我一些编译错误,例如:

Compilation error: replacements.length must be a multiple of 2
At path/to/Xxx.java line yyy (where this function was called)

Is it possible?可能吗? If possible, how to do it?如果可能,该怎么做?

Or, if this can not be achieved by using Annotations, is there any IDE or IDE plugin or some other thing can do this validation before or during compiling?或者,如果这不能通过使用注释来实现,是否有任何 IDE 或 IDE 插件或其他一些东西可以在编译之前或期间进行此验证?

Thanks.谢谢。

I would suggest to redesign your api.我建议重新设计您的 api。 Having method invocations with multiple string arguments in a row makes it difficult to tell which is the string being replaced and the replacement.连续使用多个字符串 arguments 进行方法调用使得很难判断哪个字符串被替换和替换。

I would think of something like that:我会想到这样的事情:

StringReplacement.builder()
    .replace("being replaced", "replacement")
    .replace("yet another", "replacement")
    .build()
    .replace(stringToRunReplacementsOn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM