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?
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.
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()
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.
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.
AFAIK, you can use an annotation processor to check the method signature at compile-time.
I recommend to:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With