Class cls = Class.forName("net.pbin.UpperAction"); >>>>>>1 行
Method mtd = cls.getMethod("setName",new Class[]{Integer.class}); >>>>>>2 行
obj =(Object)cls.newInstance();
mtd.invoke(obj,new Object[]{123}); >>>>>这个地方也要改再把net.pbin.UpperAction里面的name属性改成Integer,还有对应的getter和setter方法都要改掉。应该就没有问题了
invoke是动态调用Method mtd指向的方法,用obj来指明在那个实例上调用,用new Object[]{123}来为这个动态调用传递参数
Method mtd = cls.getMethod("setName",new Class[]{Integer.class}); >>>>>>2 行
obj =(Object)cls.newInstance();
mtd.invoke(obj,new Object[]{123}); >>>>>这个地方也要改再把net.pbin.UpperAction里面的name属性改成Integer,还有对应的getter和setter方法都要改掉。应该就没有问题了
invoke是动态调用Method mtd指向的方法,用obj来指明在那个实例上调用,用new Object[]{123}来为这个动态调用传递参数
如果setName(Integer name){}的话就用new Class[]{Integer.class}
我也遇到过这个问题,因为Integer和String构造函数不一样,Integer的构造函数是必须带参数的,所以你new的时候必须给个参数如 new Integer(0);而不能 new Integer();
明白了吧!!!
mtd.invoke(obj,new Object[]{123}); 不行,错误提示 cannot invoke for int to object;
必须
mtd.invoke(obj,new Object[]{new Integer(120)});