关于Java中方法参数为Void的用法
看String源码的时候发现方法参数竟然有一个参数是Void类型的,感觉很奇怪,做了这么长时间的java还是头一次发现方法参数是Void类型的,看了代码以后发现这种用法确实不错,特此记录一下
String的源码里面这个方法就用了Void做了参数,比较好奇,就去追踪的看了下。
String(char[] value, int off, int len, Void sig) {
if (len == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(value, off, len);
if (val != null) {
this.value = val;
this.coder = LATIN1;
return;
}
}
this.coder = UTF16;
this.value = StringUTF16.toBytes(value, off, len);
}
这里面调用的就是上面的方法,那么Void的参数是rangeCheck(value, offset, count)方法。
public String(char value[], int offset, int count) {
this(value, offset, count, rangeCheck(value, offset, count));
}
private static Void rangeCheck(char[] value, int offset, int count) {
checkBoundsOffCount(offset, count, value.length);
return null;
}
这里就是最后的那个方法,发现是用来做参数判断的,如果参数判断失败那么就直接抛出异常。
static void checkBoundsOffCount(int offset, int count, int length) {
if (offset < 0 || count < 0 || offset > length - count) {
throw new StringIndexOutOfBoundsException(
"offset " + offset + ", count " + count + ", length " + length);
}
}
结论
由此看来,String源码当中的Void用法就是用来校验参数的,不需要返回值,这样,在方法内部的实现就清爽多了,不用再去做校验了。当然肯定还有其他的用法,可以去挖掘。所以以后见到Void作为参数就不用奇怪了,相当于参数就是放了一个不需要返回值的方法,让它前期去做一些事情。