static public Test createTest(Class<? extends TestCase> theClass, String name) {
Constructor<? extends TestCase> constructor;
try {
constructor= getTestConstructor(theClass);
} catch (NoSuchMethodException e) {
return warning("Class "+theClass.getName()+" has no public constructor TestCase(String name) or TestCase()");
}
Object test;
try {
if (constructor.getParameterTypes().length == 0) {
test= constructor.newInstance(new Object[0]);
if (test instanceof TestCase)
((TestCase) test).setName(name);
} else {
test= constructor.newInstance(new Object[]{name});
}
} catch (InstantiationException e) {
return(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")"));
} catch (InvocationTargetException e) {
return(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")"));
} catch (IllegalAccessException e) {
return(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")"));
}
return (Test) test;
}请问test= constructor.newInstance(new Object[]{name})中new Object[]{name}是什么意思?

解决方案 »

  1.   

    生成一个放Object对象的数组,这个数组里有一个name元素
      

  2.   

    相当与你在new 对象的时候传了一个name 到你的构造方法里面去了。
    只不过这里通过反射来实现的。
      

  3.   

    通过Constructor 类,来调用目标类theClass的构造方法,此构造方法接收一个参数,这个参数是String类型的,所以就有了你写的那段代码如:
    public class Test{
    public Test(String name){
    System.out.println(name);
    }
    }
    theClass相当于Test.class;而constructor.newInstance(new Object[]{name})相当于调用了new Test(name)
      

  4.   

    向构造函数里面传参数,反射里面试Object数组,这里参数只有一个。如果有多个的话,就 constructor.newInstance(new Object[]{name1,name2, name3...})