Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

instrumentation - How to instrument java system classes?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...