Skip to content

Instantly share code, notes, and snippets.

@khotyn
Created December 6, 2012 14:45
Show Gist options
  • Save khotyn/4224925 to your computer and use it in GitHub Desktop.
Save khotyn/4224925 to your computer and use it in GitHub Desktop.
Adding an annotation to a class then redefine it
package com.khotyn.test;
import java.lang.instrument.Instrumentation;
public class AgentInstall {
public static void premain(String agentArgs, Instrumentation inst) {
InstrumentationHolder.setInstrumentation(inst);
}
}
package com.khotyn.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.UnmodifiableClassException;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Test adding an annotation to a class then redefine it.
*
* @author khotyn
*
*/
public class AnnotationAddTest {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, UnmodifiableClassException, NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
ClassReader classReader = new ClassReader(new FileInputStream(new File("D:/workspace/test/target/classes/com/khotyn/test/Test.class")));
ClassWriter classWriter = new ClassWriter(0);
ClassVisitor annotationAdder = new ClassVisitor(Opcodes.ASM4, classWriter) {
@Override
public void visitEnd() {
AnnotationVisitor av = cv.visitAnnotation(Type.getDescriptor(TestAnnotation.class), true);
if (av != null) {
av.visitEnd();
}
super.visitEnd();
}
};
classReader.accept(annotationAdder, 0);
InstrumentationHolder.getInstrumentation().redefineClasses(new ClassDefinition(Test.class, classWriter.toByteArray()));
Annotation[] annotations = Test.class.getAnnotations();
if (annotations != null && annotations.length != 0) {
System.out.println("Added annotation! " + annotations.length);
} else {
System.out.println("Empty annotation!");
}
}
}
package com.khotyn.test;
import java.lang.instrument.Instrumentation;
public class InstrumentationHolder {
private static Instrumentation instrumentation;
public static Instrumentation getInstrumentation() {
return instrumentation;
}
public static void setInstrumentation(Instrumentation instrumentation) {
InstrumentationHolder.instrumentation = instrumentation;
}
}
package com.khotyn.test;
public class Test {
}
package com.khotyn.test;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment