比如一般的调用方式
Class class = Class.forName("Test");
// Class ptypes[] ={Class.forName("java.lang.String")};
Class types[] =new Class[1];
types[0]=Class.forName("java.lang.String");//方法的参数对应下面的String aa
Method m = class.getMethod("sayHello",types );//动态调用sayHello方法
Test t = new Test();
m.invoke(t,"hellojava" );//传给方法的的参数
public class Test {
public void sayHello(String aa) {
System.out.println("Test:" + aa);
}
}
但是在应用中的service层比如:
接口 com.winneryj.service.MyService
实现 com.winneryj.service.MyServiceImpl
其中有一个方法为:
public list test(Sring str){
return myDao.getList(str);
}
上面invoke方法写法改为
Class class = Class.forName("com.winneryj.service.MyServiceImpl");
// Class ptypes[] ={Class.forName("java.lang.String")};
Class types[] =new Class[1];
types[0]=Class.forName("java.lang.String");//方法的参数对应下面的String aa
Method m = class.getMethod("sayHello",types );//动态调用sayHello方法
// Test t = new Test();
[b]请问这里的t如果换成用set方法注入的MyService,我试过无法得到,是否我的思路错误?[/b]
// m.invoke(t,"hellojava" );//传给方法的的参数
[color=darkred]
其实我的想法就是需要通过定时任务日志中记录的service调用的所有dao的执行情况,如果某些dao抛出异常,需要重新执行这些未正常执行的dao,现在的做法就是把这些dao的方法名记录下来到日志中,然后按照这些dao的方法名重新执行一遍这些dao方法[/color]
如果都是注入的dao或service,
那就不要用Class class = Class.forName("com.winneryj.service.MyServiceImpl");的方式 新建一个实例了
应该直接用已经注入的实例
在应用中的service层比如:
接口 com.winneryj.service.MyService
实现 com.winneryj.service.MyServiceImpl
其中有一个方法为:
public list test(Sring str){
return myDao.getList(str);
}
上面invoke方法写法改为
Class class = Class.forName("com.winneryj.service.MyServiceImpl");
// Class ptypes[] ={Class.forName("java.lang.String")};
Class types[] =new Class[1];
types[0]=Class.forName("java.lang.String");//方法的参数对应下面的String aa
Method m = class.getMethod("sayHello",types );//动态调用sayHello方法
[color=orange] //比如注入的service的bean的id为 myservice
//那你就应该先从spring容器得到这个myservice实例
Object myservice = context.getBean("myservice);[/color]
m.invoke(myservice ,"hellojava" );//传给方法的的参数
[code="xml"] scope="prototype">
[/code]
配置这个myService给这个包含invoke方法的类。
在applicationContext.xml中配置:
假设NameObject是方法invoke的类名。com.NameObject是类的包路径名
[code="java"] scope="prototype">
[code="java"] Class MyClass{
private ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext-*.xml");
//这样获取applicationContext
/**
* 从SchedulerFactoryBean注入的applicationContext.
*/
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
void test(){
MyService obj = (MyService)applicationContext.getBean("myService");
}
}
[/code]