开发者

How to generate a method on an annotated class?

开发者 https://www.devze.com 2023-03-14 14:57 出处:网络
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 corresp

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;
}开发者_如何学C

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


Look at using java's Proxy class you cglib Enhancer class. Both solutions allow you to proxy a class and over take any method.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消