Reputation: 8970
I wanna learn and have fun with annotations. Here is my use case: I have got a bunch of classes who basically have the same role: validate a video URL against a regex (1 method) and return the corresponding embedded HTML (another method).
The thing is the validation method is always the same. I could of course use inheritance, but I would like if it is possible to create an annotation like this:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.??)
@Inherited
@Documented
public @interface VideoProvider {
String regex();
int group() default 1;
}
Processed like that:
//processor class
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (TypeElement annotation : annotations) {
for (Element e : roundEnv.getElementsAnnotatedWith(annotation)) {
if (e.getKind().isClass()) {
//?????
}
}
}
return false;
}
The idea would be to dynamically change the annotated classes to inject a method that performs the validation. Is that feasible ?
Thanks in advance!
Rolf
Upvotes: 2
Views: 3272
Reputation: 14751
I think you're doing it wrong---
But if you really want to implement this with annotation processing at compile time, you should look at the Pluggable Annotation Processing API
This is specifically for adding annotation-driven extensions to the compilation process, to do things like automatically adding methods.
Upvotes: 0
Reputation: 34179
Look at using java's Proxy class you cglib Enhancer class. Both solutions allow you to proxy a class and over take any method.
Upvotes: 2