补发:2019-7-30 学习日记之Java基础
java函数形参之 … 省略号
有看过java反射相关一些源码的同学应该会看到这样的形参
public static void method(String... str){// ... 是什么意思?有什么用呢?
}
写个demo
public static void main(String[] args) {
String[] str = {"123","sdad"};
method("123","456","789");// 1
method(str); // 2
method(str,"abc");//报错
}
结论:
… 可以实现不确定个数的同类型参数的函数重载;
一般我们在写代码时直接将形参设为数组,实参传入也是数组的情况比较多(情况2)。用…做形参,
好处就是调用者可以随意确定传参的个数,从demo中可以看出 str 其实就是数组。
在java反射中,Class类中的各种方法也用到了这个省略号的东东
源码:Class类中的getMethod(…)方法:
public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
Method method = getMethod0(name, parameterTypes, true);
if (method == null) {
throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
}
return method;
}
真是好处多多。