方法如下:
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() {
}
关于java - 如何拦截java中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31587931/