Accessing servlet-api in javaagent

I am trying to access the classes from the servlet-api in the javaagent jar that is added to my application via the -javaagent: my-agent.jar flag. My application is running on Tomcat. The problem is I get a ClassNotFoundException because the agent container is being loaded by a classloader that doesn't have access to the servlet-api classes.

Specifically, I want to include ServletContainerInitializer in my javaagent

public class MyInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
        System.out.println(ctx);
    }
}

      

META-INF / services / javax.servlet.ServletContainerInitializer

org.example.MyInitializer

      

As a result, a ClassNotFoundException is thrown because the ServletContainerInitializer was not found.

Is there a way to access the servlet-api inside the javaagent? Or more generally, is it possible to access any class that is loaded through the ApplicationClassLoader, like the classes from the spring framework?

+3


source to share


2 answers


If your agent has a method premain

with type signature

public static void premain(String agentArgs, Instrumentation inst)

      



You get Instrumentation

an object that provides methods getAllLoadedClasses()

and getInitiatedClasses(ClassLoader)

. Now it would be awkward to search for these arrays every time and use the instances Class

only through Reflection. But you can use these methods to find the API class you want, determine its runtime, ClassLoader

and create a new ClassLoader

one by using it as the parent of the solution and pointing out your agent classes that require them.

+1


source


What worked for me, I added the servlet-api.jar file to the ClassPool.insertClassPath. And that solved the problem.

    ClassPool $pool = ClassPool.getDefault();
            try {
                $pool.insertClassPath("/apache-tomcat-7.0.50/lib/servlet-api.jar");
            } catch (NotFoundException e) {
                throw new RuntimeException(e);
            }
    return $pool;

      



https://github.com/presci/MyAgent.git

0


source







All Articles