How to intercept a method in java

Here is a way:

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

Here is the method call in the java file:

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

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

Code that I wrote in another java file, but not successfully:

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;
}
+4
source share
3 answers

Use aop programming. For example, try reading something about AspectJ.

Ex code:

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() {
}
+3
source

AFT-oriented programming (AOP) has been performed for this purpose, you can use AspectJ :

AspectJ , , , - , , , .

, Spring, Spring 2.0 AOP:

Spring 2.0 , , @AspectJ. pointcut AspectJ, Spring AOP .

:

@Aspect
public class NotVeryUsefulAspect {

}

pointCut:

@Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signature

:

+2

. , ( ). Javassist - JVM.

Cglib - , , javassist .

This tutorial is a good start: http://rafaeloltra.com/developing-a-jvm-agent-for-bytecode-instrumentation-with-javassist-pt1/ . Like the Javassist documentation: http://jboss-javassist.imtqy.com/javassist/tutorial/tutorial.html

0
source

Source: https://habr.com/ru/post/1599312/


All Articles