I want to add an annotation to all methods of some classes in a java agent, I did this and it worked , but I'm not sure if that's the right way because i saw other examples that i didn't understand. I don't understand the intercept(SuperMethodCall.INSTANCE) ? what does it mean? I don't want the class code to change in any way, its not going to be my code , it will be customer's code.
private static void premain(Instrumentation inst, boolean fromPremain) {
try {
new AgentBuilder.Default()
.type(ElementMatchers.named("com.example.TestClass"))
.transform(new AgentBuilder.Transformer() {
@Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module, ProtectionDomain protectionDomain) {
try {
AnnotationDescription annotationDescription = AnnotationDescription.Latent.Builder.ofType((Class<? extends Annotation>) Class.forName("com.example.MyAnnotation", false, classLoader)).build();
return builder
.method(ElementMatchers.isDeclaredBy(typeDescription))
.intercept(SuperMethodCall.INSTANCE)
.annotateMethod(annotationDescription);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "got exception in bytebuddy transformer", e);
return builder;
}
}
}).installOn(inst);
} catch (Throwable ex) {
LOGGER.log(Level.SEVERE, "got exception while starting agent", ex);
}
}
(Class<? extends Annotation>) Class.forName("com.example.MyAnnotation", false, classLoader)you should useClass.forName("com.example.MyAnnotation", false, classLoader) .asSubclass(Annotation.class)