反射 reflection

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; 
  }
   

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值