public class TestJunit {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void reflectionTest() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
//give the class package string;定义包名字符串,此处可以在config配置文件中配置包名和类名,在这里来读。
String packageName = "com.neusoft.domain.User";
//get class by package name;根据包名获得类
Class cls = Class.forName(packageName);
//get the method by methodName and parameterTypes;得到一个带String类型参数的函数,函数名称为toString,即:toString(String str)
Method method = cls.getMethod("toString", String.class);
//instance the class;//实例化对象
Object x = cls.newInstance();
//define the parameters of constructor;定义构造函数需要用的参数
Object[] objarr = new Object[]{"China",5,"www.baidu.com"};
//invoke the method you have get;调用方法method即:toString方法
method.invoke(this.newInstance(cls.getName(), objarr), "I love you");
}
/**
* @author xuehf
* @作用:实例化带有多参数的构造函数;若有Integer类型的参数,则转换为int.class
* @function to instance an object that who has more than one parameter use the constructor
* */
public Object newInstance(String className,Object args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
Class cls = Class.forName(className);
Class[] clsarr = new Class[args.length];
for(int i = 0;i<args.length;++i){
clsarr[i] = args[i].getClass();
if(clsarr[i].toString().equals("class java.lang.Integer")){
clsarr[i] = int.class;
}
}
Constructor cst = cls.getConstructor(clsarr);
return cst.newInstance(args);
}
}
//entity class;实体类
public class User{
private String name;
private int age;
private String email;
/**
*自动增加一些get,set方法吧
*/
public void toString(String str){
System.out.println(this.name+str);
}
/**
* define the default constructor
*/
public User(){}
/**
* define the multi-parameters constructor
*/
public User(String name,int age,String email){
this.name=name;
this.age = age;
this.email = email;
}
}
public class TestJunit { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void reflectionTest() throws ClassNotFoundException, InstantiationEx