9

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!

  • I would have expect system classes to be passed as many tools like profilers rely on this behaviour. – Peter Lawrey Nov 29 '10 at 10:38
  • Several ClassFileTransformer's could be added to avoid problems with many tools. Also there is standart/guideline/recommendations on how to transform classes – dernasherbrezon Nov 29 '10 at 10:54

1 Answers1

10

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.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • Please note that class should be checked whether it is modifiable or not: Instrumentation.isModifiable – dernasherbrezon Nov 29 '10 at 10:52
  • thanks @jarnbjo, I was looking for some thing like this - http://stackoverflow.com/questions/20282619/using-instrumentation-to-record-unhandled-exception/20283771#20283771 – Satheesh Cheveri Nov 29 '13 at 10:40