I’m using java 6 annotation processing api. I have followed the following excellent tutorial for creating an annotation processor that displays a message at build-time:
http://kerebus.com/2011/02/using-java-6-processors-in-eclipse/
However, in my case, I have a simple class as such:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Criteria {
String id();
double width();
double height();
}
As you can see, the aforementioned annotation is made available to the JVM at runtime using the meta-annotation ‘Retention’. I use this ‘Criteria’ annotation in the source code of another class to annotate a method, like so:
@Criteria(id = "fooBar",
width = 22,
height = 10
)
public void fooStream() {
System.out.println("foo stream method");
}
At runtime, I want to include the ‘fooStream’ method in another class, ONLY if variables that are passed in match the values of the elements in the @Criteria annotation, namely ‘width’ and ‘height’. My question is, how could I take the method ‘fooStream’ and inject this into another class at run-time? Is this even possible? I’m not looking for any code examples, just answers to the two aforementioned questions. Also, in the link at the top, there is an example of generating a code using ‘JavaFileObject’ and ‘Writer’ instances, where the generated code is passed as a string.
If you want runtime modification of you classes, you can use your own classloader and intercept loading of classes, introspect what you want and generate new bytecode using asm library instead of original classes. It is not very tricky, but you must be sure you need exactly that.