我对“类加载”概念和 javaagent 有点困惑。
假设我有一个这样的代理类:
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
}
});
}
}
我通过将 Premain-Class
设置为 Agent
类来创建代理 jar。
现在我在我的 VM 使用 -javaagent
启动时传递这个代理 jar,所以问题是:
premain
什么时候会被调用?仅当类加载器加载类时?如果是这样,那么对于每个类在bootstrap
、extension
、system
加载器中,这个premain
只被调用一次?或者我什么时候创建一个类的对象然后调用它的方法?
最佳答案
代理的premain
方法会被调用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.
关于java - 在什么情况下将调用 Java Agent premain 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35330906/