Compell method with specific annotation to have specific parameters / signature

I have an annotation like:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String annotationArgument1() default "";
    String annotationArgument2();
}

      

I have two classes:

class MyClass1 {
    @MyAnnotation(annotationArgument1="ABC", annotationArgument2="XYZ")
    public void method1(MyClass2 object) {
        //do something
    }

    @MyAnnotation(annotationArgument1="MNO", annotationArgument2="PQR")
    public void method2(MyClass2 object) {
        //do something
    }
}

class MyClass2 {
    int num;
}

      

I want method1

and method2

(or any other method in any other class, annotated with @MyAnnotation

), only accept one argument as MyClass2

, because they are annotated with @MyAnnotation

. If any other argument is passed, it should give a compile-time error.

Is it really possible? If so, how can this be done, and if not, what is the alternative to make this behavior possible?

+3


source to share


1 answer


AFAIK, you can use an annotation processor to check the method signature at compile time.

I recommend:



  • consider AbstractProcessor as a base class
  • consider using the annotations provided by the javax.annotation.processing package
  • register the Processor as a service in META-INF / services
  • package your annotation and annotation processor in the same jar - along with registering as a service, this will enable the processor whenever your custom annotation processor is used.
+2


source







All Articles