I'm getting bit confused on "class loading" concept along with javaagent.
Lets say I have an agent class like this:
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class Agent {
public static void premain(String agentArgs, Instrumentation inst) {
inst.addTransformer(new ClassFileTransformer() {
@Override
public byte[] transform(ClassLoader classLoader, String s, Class<?> aClass, ProtectionDomain protectionDomain, byte[] bytes) throws IllegalClassFormatException {
// ASM Code for changing the bytecodes
}
});
}
}
and I create an agent jar by setting up the Premain-Class
to the Agent
class.
Now I'm passing this agent jar while my VM start up using -javaagent
, so the question is:
At what times the premain
will be getting called? Only when class loaded by the classloaders? If so then this premain
is called exactly once for each class is in bootstrap
,extension
,system
loaders?
Or when ever I create a object of a class and then call its methods?
The premain
method of an agent will be called once.
After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.