首先描述问题
public ClassName() 和public ClassName(Object…parameters)是否是同一个函数?
俺的回答是不是滴,看测试代码
1: public class Test
2: {
3: public Test()
4: {
5: System.out.println("No Constructor");
6: }
7: public Test(Object...keys)
8: {
9: System.out.println("Paramterized");
10: }
11: public static void main(String[] argvs)
12: throws Exception
13: {
14: Test a=new Test();
15: }
16: }
如果两个构造函数是一样的,则不可能编译通过,所以不同。实际上,在函数签名上也是有很大区别的,看main函数中的调用,这个默认函数的调用是“类的默认构造函数”。
我们再看看下面的例子:
1: public class Test
2: {
3: // public Test()
4: // {
5: // System.out.println("No Constructor");
6: // }
7: public Test(String...keys)
8: {
9: System.out.println("Paramterized");
10: }
11: public static void main(String[] argvs)
12: throws Exception
13: {
14: Test a=new Test();
15: }
16: }
注释掉之后没问题了,直接调用的可变参数的函数。那么试试传说中的反射构造捏:
1: public static void main(String[] argvs)
2: throws Exception
3: {
4: java.lang.reflect.Constructor c = Test.class.getConstructor();
5: System.out.println(null==c?"Not found":"found");
6: }
很遗憾,出错鸟:
Exception in thread "main" java.lang.NoSuchMethodException: com.jeasonzhao.report.engine.test.Test.<init>()
at java.lang.Class.getConstructor0(Class.java:2647)
at java.lang.Class.getConstructor(Class.java:1629)
at com.jeasonzhao.report.engine.test.Test.main(Test.java:20)
这就是说,根本找不到这个东东啊。所以,间接证明了两个构造函数不同,但是,以下的两个是不是一样地呢?
1: public Test(String...keys)
2: {
3: System.out.println("Paramterized");
4: }
5: public Test(String[] argc)
6: {
7: System.out.println("String Array Paramterized");
8: }
在IDE中,编译不通过,出现了名字重复,实际上,这两个倒是一样的。
再玩点花哨的:
1: public Test(Object ...argc)
2: {
3: System.out.println("Object Array Paramterized");
4: if(null != argc)
5: {
6: int nid=0;
7: for(Object o : argc)
8: {
9: System.out.println("\t"+(nid++)+"> " + (null == o ? "[NULL]" : o.toString()));
10: }
11: }
12: }
13:
14: public static void main(String[] argvs)
15: throws Exception
16: {
17: Test t = new Test(1,"S"
18: ,new String[]{"I AM IN STRING ARRAY","STRING ARRAY END"}
19: ,new Object[]{"OBJ1","OBJ2"}
20: ,null
21: ,"END");
22: Test t2=new Test(new String[]{"I AM IN STRING ARRAY","STRING ARRAY END"});
23: Test t3=new Test(new Object[]{"OBJ1","OBJ2"});
24: }
猜测一下,输出应该是什么?
关键是怎么处理那个String[]和Object[].
结果是:
Object Array Paramterized
0> 1
1> S
2> [Ljava.lang.String;@1c78e57
3> [Ljava.lang.Object;@5224ee
4> [NULL]
5> END
Object Array Paramterized
0> I AM IN STRING ARRAY
1> STRING ARRAY END
Object Array Paramterized
0> OBJ1
1> OBJ2
至于为什么,自己去想吧,很浅显的