Search code examples
javaclassruntimeclassloaderinstrumentation

Java: How to intercept classes as they are being loaded by the JVM


In my program I want to intercept classes as they are being loaded by their ClassLoader and do some stuff with them eg. check for certain annotations etc. How do I do this?

I have already done a lot of research online but have not gotten my answer. Should I perhaps override ClassLoader? The problem with that is that the parent ClassLoader gets to load the class in most cases, so I won't be able to get ALL classes. On a couple questions on this site I've seen Instrumentation get mentioned, but I don't know if that is relevant to my problem.


Solution

  • You can use java agents to monitor this:

    API doc: http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/ClassFileTransformer.html

    Example:

    http://www.informit.com/guides/content.aspx?g=java&seqNum=589