Is there any way to predefine length of an array parameter by annotations

亡梦爱人 提交于 2021-01-28 06:16:10

问题


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
    }

回答1:


Yes, this is possible, using a compiler plugin.

Use the @ArrayLen annotation to declare a method whose argument must be a length-9 array of Strings:

void myMethod(String @ArrayLen(9) [] a) {
  ...
}

Then, compile your program using the Index Checker of the Checker Framework:

javac -processor index MyJavaFile.java

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.




回答2:


You can't enforce it on an array (length is not part of the array type in Java, unlike some other languages).

However, you can define a class like this:

final class IntArrayWithLength9 {  // Obv you can use a better name.
  private final int[] arr = new int[9];

  void set(int i, int value) { arr[i] = value; }
  int get(int i) { return arr[i]; }
}

Now, you know that if you've got an instance of this class, then the array has length 9, thus you don't need to check it.

So, you can now use IntArrayWithLength9 instead of int[].



来源:https://stackoverflow.com/questions/50122408/is-there-any-way-to-predefine-length-of-an-array-parameter-by-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!