如何在Java中拦截方法 [英] How to intercept a method in java

查看:938
本文介绍了如何在Java中拦截方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是方法:

public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh)

这是java文件中的方法调用:

Here is the method call in a java file:

WebModuleUtil.startModule(module, getServletContext(), false);

我无法对这些文件进行任何更改,但是我想拦截该方法并添加一些代码(我也希望访问参数)

I cannot make any changes to these files, but I want to intercept the method and add some of my code (I want access to the parameters as well)

我在另一个Java文件中编写的代码,但未成功:

Code I wrote in another java file but not successful:

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的内容.

Use aop programming. For example try to read something about 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() {
}

这篇关于如何在Java中拦截方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆