Mukund Jalan
Mukund Jalan

Reputation: 1339

Compel a method with specific annotation to have specific parameters/signature

I have an annotation as:

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 as:

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) to take only one argument as MyClass2 because they are annotated with @MyAnnotation. If some other argument is passed, it must give a compile time error.

Is it actually possible to do this? If yes, how can it be done and if no, what is alternate to make this kind of behavior possible?

Upvotes: 7

Views: 2666

Answers (1)

Puce
Puce

Reputation: 38132

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

I recommend to:

  • consider AbstractProcessor as a base class
  • consider to use the annotations provide by the javax.annotation.processing package
  • register the Processor as a service in META-INF/services
  • package the annotation processor and the annotations in the same jar - together with the registration as a service this will enable the processor whenever your custom annotation processor is used

Upvotes: 3

Related Questions