如何在java中拦截方法
方法如下:如何在java中拦截方法,java,spring,methods,intercept,Java,Spring,Methods,Intercept,方法如下: public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) 以下是java文件中的方法调用: WebModuleUtil.startModule(module, getServletContext(), false); 我无法对这些文件进行任何更改,但我想截取该方法并添加一些代码(我还想访问参数) 我在另一个java文件中编写的代
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh)
以下是java文件中的方法调用:
WebModuleUtil.startModule(module, getServletContext(), false);
我无法对这些文件进行任何更改,但我想截取该方法并添加一些代码(我还想访问参数)
我在另一个java文件中编写的代码,但未成功:
public void main(String[] args) throws Exception {
Module module = null;
WebModuleUtil wmb = new WebModuleUtil();
ProxyFactory pf = new ProxyFactory(wmb);
pf.addAdvice(new MethodInterceptor() {
public Object invoke(MethodInvocation invocation) throws Throwable {
if (invocation.getMethod().getName().startsWith("start")) {
System.out.println("method " + invocation.getMethod() + " is called on " + invocation.getThis()
+ " with args " + invocation.getArguments());
System.out.println("********************");
Object ret = invocation.proceed();
System.out.println("method " + invocation.getMethod() + " returns " + ret);
return ret;
}
return null;
}
});
WebModuleUtil proxy = (WebModuleUtil) pf.getProxy();
proxy.startModule(module, getServletContext(), false);
}
private static ServletContext getServletContext() {
// TODO Auto-generated method stub
return null;
}
使用aop编程。例如,尝试阅读有关AspectJ的内容 Ex代码:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Service;
@Aspect
@Service
public class AspectDemo {
@Around("aop1()" )
public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable {
for (Object obj : joinPoint.getArgs()) {
LOG.debug(obj);
}
}
@Pointcut("execution(*my.example.packcage.startModule.*(..))")
public void aop1() {
}
面向方面编程(AOP)就是为此目的而设计的,您可以使用: AspectJ支持横切关注点的清晰模块化,如错误检查和处理、同步、上下文敏感行为、性能优化、监视和日志记录、调试支持以及多对象协议 或者在使用
Spring
时,您可以使用:
Spring2.0引入了一种更简单、更强大的方式,使用基于模式的方法或@AspectJ注释样式编写自定义方面。这两种风格都提供了全类型的建议和AspectJ切入点语言的使用,同时仍然使用SpringAOP进行编织
以下是如何声明方面:
@Aspect
public class NotVeryUsefulAspect {
}
下面是如何声明切入点:
@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature
有关更多信息,您可以参考以下教程:
以及Javassist文档:您说您不能更改WebModuleUtil类,但是使用该方法的类呢?你能改变它的调用方式吗?你需要编程一个方面。方面适合于这样的任务本身。