Callback using annotations

Viewed 81

I am trying to create an Experimental annotation. My goal is to be able to use it in any method, variable or class declaration, and when the program is run, for every time an Element with the Experimental annotation, a warning should be sent to the console, reminding the user that they are working with experimental stuff. Something like this:


@Experimental // Maybe this should go above the constructor? I'm not sure, the class itself is experimental, not just the specific constructor
public class MyClass {

    public MyClass() {
        // Constructor stuff
    }

    @Experimental
    public void myExperimentalMethod(){
        // Just a method that is still in its experimental state
    }

}

public class Program {
    public static void main(String[] args) {
        MyClass myClass = new MyClass(); // When this line is run, a warning should be sent to the console

        myClass.myExperimentalMethod(); // This line should also send a warning to the console
    }
}

So far, I have my own annotation interface, like so:

import java.lang.annotation.*;

/**
 *
 * This element has experimental maturity.  Use with caution.
 *
 *
 * NOTE: The developers of this element is not responsible for the issues created,
 * using it is not suggested for production environment.
 */


@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,
        ElementType.CONSTRUCTOR, ElementType.LOCAL_VARIABLE, ElementType.PACKAGE,
        ElementType.ANNOTATION_TYPE, ElementType.TYPE_USE, ElementType.TYPE_PARAMETER
})
public @interface Experimental {

}

But it does nothing, it just sits on top of an Element and acts like a regular comment, so as of right now it is just an eye-catching comment. I've read about Annotation Processors, but everything I've found is for processing the source file, and they don't work on runtime. As you can imagine, I'm not really familiar with annotations, but they seem like the right way to implement this feature.

Now, straight to the point: How can I execute code (wether it is using a callback, or a method, or whatever) every time an Element with a specific Annotation is used in runtime?

0 Answers
Related