How to instrument java system classes?

帅比萌擦擦* 提交于 2019-11-27 12:31:14

问题


I'm trying to add custom behaviour to system classes (FileInputStream/FileOutputStream). I wrote custom ClassFileTransformer with the following transform method:

public byte[] transform(ClassLoader arg0, String arg1, Class arg2, ProtectionDomain arg3, byte[] arg4) throws IllegalClassFormatException {
    System.out.println("class name: " + arg1);
    return arg4;
}

When I run sample program:

public static void main(String[] args) throws Exception {
    new FileOutputStream("file");
}

I see that no system classes are not passed to transform.

Is there any way to modify system classes? Thanks in advance!


回答1:


Some (not all) system classes are already loaded before the pre-main method is invoked and your ClassFileTransformer is added. If you want to transform these classes as well, you can invoke something like Instrumentation#retransformClasses(Instrumentation#getAllLoadedClasses()) after adding your ClassFileTransformer. Note, you have to use Instrumentation#addTransformer(ClassFileTransformer, true) to indicate that your transformer supports retransformation of classes.



来源:https://stackoverflow.com/questions/4302862/how-to-instrument-java-system-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!