kris14an
kris14an

Reputation: 751

Reflection geting value from method argument annotation

Sample code:

public interface TestClass {

    @AnnoTest
    public Object getTestObject( @AnnoTestArg("id") Integer postId );

}

How can i get value from @AnnoTestArg annotation ? I know how to check is argument annotated but, i can't check annotation value.

That's my code:

public void build(...) {
    Annotation[][] anno = pm.getMethod().getParameterAnnotations();

    for( Annotation a : anno[argNumber] ) {
        if( a.equals(AnnoTestArg.class) ) {
            // value ?
        }
    }


    return connector;
}

Upvotes: 0

Views: 80

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279890

Annotation is the superinterface of all annotation types. Assuming your AnnoTestArg annotation is something like

@Target(value = ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@interface AnnoTestArg {
    String value();
}

you can just cast the Annotation value to AnnoTestArg and invoke the appropriate method

for (Annotation a : anno[0]) {
    if (a instanceof AnnoTestArg) {
        AnnoTestArg arg = (AnnoTestArg) a;
        System.out.println(arg.value());
    }
} 

Upvotes: 1

Related Questions