views:

275

answers:

3

Is it possible to insert a javaagent after virtual machine start from within the same VM?

Lets say for example we have an agent in a jar myagent.jar with the appropriate meta data set-up and an agentmain method already implemented. Now the users program calls an API call which should result in the insertion of the agent so that it can redefine the classes.

Can it be done and how?

A: 

By using daemon threads we can start a java agent. Which can handle these operations.

cdb
+1  A: 

You should be able to do it in Java 6, see the package documentation chapter "Starting Agents After VM Startup"

edit: Maybe it was possible in Java 5 already and just the javadocs didn't mention it that explicitly

HerdplattenToni
It does not specify what the method call is however. Looking further into it however would ((URLClassLoader)ClassLoader.getSystemClassLoader()).addURL(....) where the URL added pointed to the myagent.jar result in the agentmain being called?
Paul Keeble
Is this Java 6 in general or only with HotSpot?
Thorbjørn Ravn Andersen
@Paul: I haven't tried it so I can't say if it works like that but it seems reasonable. However you will have to call addURL by reflection since it is protected.Something like:URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { Method method = sysclass.getDeclaredMethod("addURL",parameters); method.setAccessible(true); method.invoke(sysloader,new Object[]{ yourURL }); }
HerdplattenToni