public static byte[] instrument(byte[] originalBytes,String recorderClass,String recorderMethod,ClassLoader loader){
  try {
    ClassReader cr=new ClassReader(originalBytes);
    ClassWriter cw=new StaticClassWriter(cr,ClassWriter.COMPUTE_FRAMES,loader);
    VerifyingClassAdapter vcw=new VerifyingClassAdapter(cw,originalBytes,cr.getClassName());
    ClassVisitor adapter=new AllocationClassAdapter(vcw,recorderClass,recorderMethod);
    cr.accept(adapter,ClassReader.SKIP_FRAMES);
    return vcw.toByteArray();
  }
 catch (  RuntimeException e) {
    logger.log(Level.WARNING,"Failed to instrument class.",e);
    throw e;
  }
catch (  Error e) {
    logger.log(Level.WARNING,"Failed to instrument class.",e);
    throw e;
  }
}

public static byte [ ] instrument ( byte [ ] originalBytes , String recorderClass , String recorderMethod , ClassLoader loader ) { try { ClassReader cr = new ClassReader ( originalBytes ) ; ClassWriter cw = new StaticClassWriter ( cr , ClassWriter . COMPUTE_FRAMES , loader ) ; VerifyingClassAdapter vcw = new VerifyingClassAdapter ( cw , originalBytes , cr . getClassName ( ) ) ; ClassVisitor adapter = new AllocationClassAdapter ( vcw , recorderClass , recorderMethod ) ; cr . accept ( adapter , ClassReader . SKIP_FRAMES ) ; return vcw . toByteArray ( ) ; } catch ( RuntimeException e ) { logger . log ( Level . WARNING , "Failed to instrument class." , e ) ; throw e ; } catch ( Error e ) { logger . log ( Level . WARNING , "Failed to instrument class." , e ) ; throw e ; } }
given the bytes representing a class , go through all the bytecode in it and instrument any occurences of new / newarray / anewarray / multianewarray with pre - and post - allocation hooks . even more fun , intercept calls to the reflection api ' s array . newinstance ( ) and instrument those too .
