有没有办法通过注释预定义数组参数的长度 [英] Is there any way to predefine length of an array parameter by annotations
问题描述
我正在开发一个数独解决应用程序,但我不想编写诸如
I'm working on a sudoku solving application and i dont want to write a code such as
Method(int[] i)
{
if(i.length == 9)
{
// do stuff
}
else
{
// throw...
}
}
有什么方法可以通过使用诸如
is there any way to enforce arrays parameter to be exact 9 integer by using annotations such as
Method(@SizeNine int[] i)
{
//do stuff
}
推荐答案
是的,这是可能的,使用编译器插件.
Yes, this is possible, using a compiler plugin.
使用@ArrayLen
注释声明一个方法,其参数必须是一个长度为 9 的字符串数组:
Use the @ArrayLen
annotation to declare a method whose argument must be a length-9 array of Strings:
void myMethod(String @ArrayLen(9) [] a) {
...
}
然后,使用 Index Checker 编译您的程序https://checkerframework.org/manual/" rel="nofollow noreferrer">检查框架:
Then, compile your program using the Index Checker of the Checker Framework:
javac -processor index MyJavaFile.java
现在,如果任何客户端尝试传递长度不能保证为 9 的数组,javac 将发出编译时警告.如果有警告,您可以修复它并重新编译.无需在您的实现中对数组长度执行运行时检查.
Now, javac will issue a compile-time warning if any client tries to pass an array whose length is not guaranteed to be 9. If there is a warning, you can fix it and re-compile. There is no need to perform a run-time check of the array length within your implementation.
这篇关于有没有办法通过注释预定义数组参数的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!