Java annotation execute a method within the annotation declaration(usage for android) Java annotation execute a method within the annotation declaration(usage for android) android android

Java annotation execute a method within the annotation declaration(usage for android)


Annotations are meta data. What you need to write is an annotation processor. An annotation in itself cannot accomplish the validation logic. The annotation processor will look at the annotations and then do the validation and control the application flow. This SO answer has a good explanation Can Java Annotations help me with this?

You also need to annotate the annotation with @Retention(RetentionPolicy.RUNTIME) so that the annotation information is preserved till the runtime.

@Retention(RetentionPolicy.RUNTIME) public @interface Validate() {}


Note, this might be quite off-topic. Using spring AOP with, processing the annotations is fairly straightforward:

Create an aspect:

@Aspectpublic class RoleCheckAspect {  @Before("@annotation(your.package.Validate)")  public void doAccessCheck() throws Exception {    // Do validation stuff    if (!valid)      throw new IllegalAccessException("foo");    }  }}

Set-up your aspect:

In META-INF/aop.xml

<!DOCTYPE aspectj PUBLIC  "-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd"><aspectj>  <weaver>    <!-- only weave classes in our application-specific packages -->    <include within="your.package..*" />  </weaver>  <aspects>    <!-- weave in just this aspect -->    <aspect name="com.bac.bsl.nonproc.TestAspect" />  </aspects></aspectj>

Set-up load time weaving

In the spring context:

<context:load-time-weaver/> 

Ensure that the spring-agent is started with your app:

java -javaagent:/path/to/spring-agent.jar -classpath $CP your.package.MyApp


I don't think you can achieve this with annotations alone. They are meant to provide meta information about code elements and not processing logic.To actually implement the restriction on the annotated methods invocation you will need to check the access by hand inside or outside the method or inject such a check using something like http://www.eclipse.org/aspectj/