The Artima Developer Community
Sponsored Link

Java Buzz Forum
JDK1.5: java.lang.instrument

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Nick Lothian

Posts: 397
Nickname: nicklothia
Registered: Jun, 2003

Nick Lothian is Java Developer & Team Leader
JDK1.5: java.lang.instrument Posted: Jan 27, 2004 4:57 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Nick Lothian.
Original Post: JDK1.5: java.lang.instrument
Feed Title: BadMagicNumber
Feed URL: http://feeds.feedburner.com/Badmagicnumber
Feed Description: Java, Development and Me
Latest Java Buzz Posts
Latest Java Buzz Posts by Nick Lothian
Latest Posts From BadMagicNumber

Advertisement

The java.lang.instrument package allows a programmer to modify classfiles as they are loaded. No API for doing the modifications is supplied, but you can use ASM or BCEL etc to do that. This example prints out class names as they are loaded.


package inst;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;

public class Instrument {

    public static void premain(String options, Instrumentation ins) {
    	ins.addTransformer(new Logger() );
    }

    public static void main(String args[] ) {
    	System.out.println("Hello World" );
    }

    public static class Logger implements ClassFileTransformer {
        public byte[] transform(java.lang.ClassLoader loader,
                java.lang.String className,
                java.lang.Class classBeingRedefined,
                java.security.ProtectionDomain protectionDomain,
                byte[] classfileBuffer) throws IllegalClassFormatException
        {
            System.err.println(className );
            return null;
        }
    }

}

It is run using the new javaagent parameter:

   java -javaagent:inst.Instrument inst.Instrument

Output:


    java/lang/StringCoding
    java/lang/ThreadLocal$ThreadLocalMap
    java/lang/ThreadLocal$ThreadLocalMap$Entry
    java/lang/StringCoding$CharsetSD
    java/lang/StringCoding$StringDecoder
    Hello World
I presume that classes like java.lang.String are loaded prior to the agent class being hooked up. Also, beware that it is possible to deadlock the classloading mechanism if you aren't careful - only modifying classes that don't match a regexp like "java.*|sun.*|javax.*" is a good idea!

Read: JDK1.5: java.lang.instrument

Topic: Swixml: 1st runner-up Previous Topic   Next Topic Topic: Franklin 2004

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use