Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compell 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?

like image 582
Mukund Jalan Avatar asked Jun 12 '15 08:06

Mukund Jalan


People also ask

Does method signature include parameters?

A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types.

What determines the signature of a method?

The signature of a method consists of the name of the method and the description (i.e., type, number, and position) of its parameters. Example: toUpperCase()

What is parameter signature in Java?

In Java, a method signature is part of the method declaration. It's the combination of the method name and the parameter list. The reason for the emphasis on just the method name and parameter list is because of overloading. It's the ability to write methods that have the same name but accept different parameters.

Can a method signature have a method body?

According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.


1 Answers

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
like image 195
Puce Avatar answered Oct 08 '22 04:10

Puce