有什么办法可以通过注释预定义数组参数的长度 [英] Is there any way to predefine length of an array parameter by annotations

查看:54
本文介绍了有什么办法可以通过注释预定义数组参数的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发数独解决方案,我不想编写诸如

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) {
  ...
}

然后,使用现在,如果任何客户机尝试传递其长度不能保证为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆