Thursday, November 15, 2012

Meta-Annotations


Meta-Annotations

Meta-Annotations are an experiment in annotation inheritance, abstraction and encapsulation with a Java SE mindset
A meta-annotation is any annotation class annotated with @Metatype. The other annotations used on the meta-annotation become part of its definition. If any of those annotations happen to also be meta-annotations, they are unrolled as well and their annotations become part of the definition.

@Metatype

The recursion that is the meta-annotation concept only happens when an annotation is marked as a @javax.annotation.Metatype.
When @Metatype is seen the basic contract is "carry the surrounding annotations forward". When a class, method or other target uses an annotation annotated with @Metatype the annotations on that annotation are "unrolled" or carried forward and effectively placed on that class, method or other target as if they were explicitly declared.
If any of the annotations that are carried forward also are annotated with @Metatype the recursion continues. The result is a simple algorithm or design pattern that provides inheritance or reuse in a way that is not specific to any domain, API, or specification.
APIs and specifications can choose to formally adopt annotation reuse in this fashion, but the core concept and implementations of@Metatype do not need to be expanded to support these APIs or specifications.
The simple elegance of this not being domain specific is that it could be used to combine several annotations from different specifications into one reusable annotation. Say JAX-RS @PathParam("id") with Bean Validation @NotNull to create a new annotation called @ValidId.

Creating Meta-Annotations

If the annotation in question can be applied to ElementType.ANNOTATION_TYPE or ElementType.TYPE, creating a meta-annotation version of it is quite easy.
@TransactionManagement(TransactionManagementType.CONTAINER)
@Metatype
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContainerManagedTransactions {
}
When the annotation in question cannot be applied to ElementType.ANNOTATION_TYPE or ElementType.TYPE, things get interesting. This is where meta-annotations depart from things like @Stereotype. The goal of meta-annotations is to be completely generic and not specific to any one domain or API. A such, you cannot really require all existing APIs change to allow for meta-annotations. The goal is that meta-annotations can be used generically and do not need to be "designed" into an API.
To allow annotations that apply to FIELDMETHODPARAMETERCONSTRUCTORLOCAL_VARIABLE, or PACKAGE, as well as any other location where annotations may be applied in the future a compromise is made.
import javax.ejb.Schedule;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Metatype
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

public @interface Daily {
    public static class $ {

        @Daily
        @Schedule(second = "0", minute = "0", hour = "0", month = "*", dayOfWeek = "*", year = "*")
        public void method() {
        }
    }
}
An inner class named $. This is enough to bind together the @Daily and @Schedule in the context to which they both apply.
Ugly but effective. Alternate proposals welcome.
The above is considered the public API portion of the meta-annotation concept.
The concept itself is born out of standards based systems like EJB and CDI where annotation processing is invisible to the application itself. In those settings the above is enough and no additional APIs would be needed to support meta-annotations in standard APIs.

Under the covers

The "guts" of this particular implementation is designed to look and feel as much like the reflection API as possible. Obviously, with VM level control, you could do much better. A clean Java SE API might be just what is needed and its very possible that meta-annotations should really be a Java SE concept.
Here's a glimpse as to how things can look under the covers:
final java.lang.reflect.AnnotatedElement annotated = new org.metatype.MetaAnnotatedClass(Triangle.class);
assertNotNull(annotated);

assertTrue(annotated.isAnnotationPresent(Color.class));
assertTrue(annotated.getAnnotation(Color.class) != null);
assertTrue(!contains(Color.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Color.class, annotated.getAnnotations()));
assertEquals("red", annotated.getAnnotation(Color.class).value());

assertTrue(annotated.isAnnotationPresent(Red.class));
assertTrue(annotated.getAnnotation(Red.class) != null);
assertTrue(!contains(Red.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Red.class, annotated.getAnnotations()));

assertTrue(annotated.isAnnotationPresent(Crimson.class));
assertTrue(annotated.getAnnotation(Crimson.class) != null);
assertTrue(contains(Crimson.class, annotated.getDeclaredAnnotations()));
assertTrue(contains(Crimson.class, annotated.getAnnotations()));
The application classes would look like so:
@Crimson
// -> @Red -> @Color
public static class Triangle {

}

@Metatype
@Color("red")
// one level deep
@Target(value = {TYPE})
@Retention(value = RUNTIME)
public static @interface Red {
}

@Metatype
@Red
// two levels deep
@Target(value = {TYPE})
@Retention(value = RUNTIME)
public static @interface Crimson {
}

Best Practices
It is recommended to have an api package or some other package where "approved' annotations are defined and to prohibit usage of the non-meta versions of those annotations. All the real configuration will then be centralized in the api package and changes to the values of those annotations will be localized to that package and automatically be reflected throughout the application.
An interesting side-effect of this approach is that if the api package where the meta-annotation definitions exist is kept in a separate jar as well, then one can effectively change the configuration of an entire application by simply replacing the api jar.

Future concepts

XML Overriding

The unrolling of meta-annotations happens under the covers. In that same vein, so could the concept of overriding.
The above @Red annotation might theoretically be overridden via xml as follows:

<org.superbiz.api.Red>
  <org.superbiz.api.Color value="dark red"/>
</org.superbiz.api.Red>
Or take more complex meta-annotation definition like the following:
package org.superbiz.corn.meta.api;

import javax.ejb.Schedule;
import javax.ejb.Schedules;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Metatype
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)

public @interface PlantingTime {
    public static interface $ {

        @PlantingTime
        @Schedules({
                @Schedule(month = "5", dayOfMonth = "20-Last", minute = "0", hour = "8"),
                @Schedule(month = "6", dayOfMonth = "1-10", minute = "0", hour = "8")
        })
        public void method();
    }
}
This might theoretically be overridden as:

<org.superbiz.corn.meta.api.PlantingTime>
  <javax.ejb.Schedules>
    <value>
      <javax.ejb.Schedule month="5" dayOfMonth="15-Last" minute="30" hour="5"/>
      <javax.ejb.Schedule month="6" dayOfMonth="1-15" minute="30" hour="5"/>
    </value>
  </javax.ejb.Schedules>
</org.superbiz.corn.meta.api.PlantingTime>

Merging or Aggregating definitions
Certain annotations take lists and are designed to be multiples. In the current definition of meta-annotations, the following is illegal.
@RolesAllowed({"Administrator", "SuperUser"})
@Metatype
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Admins {
}

@RolesAllowed({"Employee", "User"})
@Metatype
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Users {
}


public static class MyBean {

    @Admin
    @User
    public void doSomething() {
        // ...
    }
}
Here the @Admin and @User annotation each resolve to @RolesAllowed. Since only one @RolesAllowed annotation is allowed on the method per the Java language specification, this results in an error.
The intention is clear however and aggregating metadata together in this way is natural.
A theoretical way to support something like this is with an annotation to describe that this aggregation is intended and desired. Note the addition of the theoretical @Merge annotation.
@RolesAllowed({"Administrator", "SuperUser"})
@Metatype
@Merge
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Admins {
}

@RolesAllowed({"Employee", "User"})
@Metatype
@Merge
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Users {
}


public static class MyBean {

    @Admin
    @User
    public void doSomething() {
        // ...
    }
}
A new @RolesAllowed annotation would be created containing the list {"Administrator", "SuperUser", "Employee", "User"} and that would represent the final @RolesAllowed usage for the doSomething() method.

236 comments:

«Oldest   ‹Older   201 – 236 of 236
ganesh said...

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

Angular js Training in Chennai

Angular js Training in Velachery

Angular js Training in Tambaram

Angular js Training in Porur

Angular js Training in Omr
Angular js Training in Annanagar

harini said...

This is an amazing post. Very informative and expressed in a precise way. Its a must recommend post! thanks for such a great content! Loved reading it. Thanks for your time in extracting the information.
Selenium Training in Chennai

Selenium Training in Velachery

Selenium Training in Tambaram

Selenium Training in Porur

Selenium Training in Omr

Selenium Training in Annanagar

HOT AND SEXY INDEPENDENT ESCORTS IN LUCKNOW said...

THANK YOU FOR VISITING MY WEBSITE:-
russian escorts in gurgaon
housewife escorts in gurgaon
gurgaon escort services
gurgaon escorts
escorts in gurgaon
escort services in gurgaon
gurgaon call girls
call girls in gurgaon

sahasrit said...

Thanks for sharing the information..... keep sharing more articles.
amazon web services aws training in chennai

microsoft azure training in chennai

workday training in chennai

android-training-in chennai

ios training in chennai

Ms Nikita Agarwal said...

I really loved your post so much that I cant resist writing comment...Please check mine as well
Escorts in Jaipur
Escorts in Jaipur
Escorts in Jaipur
Escorts in Delhi
Escorts in Guwahati
Escorts in Guwahati
Escorts in Guwahati
Escorts in Guwahati
Escorts in Lucknow

Hemachandran said...

Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for a sharing.
Java training in chennai

python training in chennai

web designing and development training course in chennai

selenium training in chennai

digital-marketing seo training in chennai

Anonymous said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
salesforce course in chennai

software testing course in chennai

robotic process automation rpa course in chennai

blockchain course in chennai

devops course in chennai

Mohd Sharique said...

This information is impressive..I am inspired with your post writing style & how continuously you describe this topic.

Online Training for Big Data
best Apache Spark online course

siva said...

This is an excellent blog. Keep sharing the blog.
how to pass ielts
ethical hacking course requirements
stress interview questions and answers
core java for selenium
ethical hacking technical interview questions

Joe said...

Tube fittings
Manifold valves
Needle valve
Ball valve
hadoop training in chennai

Babu said...

Great experience I got good information from your blog.
devops roles and responsibilities
7 habits
mobile automation testing tools
benefits of web designing
excel interview questions and answers

Lavanya said...

Good and nice blog post, thanks for sharing your information.. it is very useful to me.. keep rocks and updating..
salesforce training in chennai

software testing training in chennai

robotic process automation rpa training in chennai

blockchain training in chennai

devops training in chennai

Williams said...

This is an excellent blog. Really very creative and informative content.
artificial intelligence advantages
application of asp net
definition of hadoop
devops tools java
selenium interview questions and answers pdf
selenium webdriver interview questions and answers

Magesh said...

It is really good and thanks for your useful post...
Social Media Marketing Courses in Chennai
Social Media Marketing Training in Chennai
Social Media Marketing Online Course

Deekshitha said...

very informative blog
data science training in Pune

Huongkv said...

Aivivu - chuyên vé máy bay, tham khảo

kinh nghiệm mua vé máy bay đi Mỹ giá rẻ

các chuyến bay từ mỹ về việt nam hôm nay

các đường bay từ canada về việt nam

Lịch bay từ Hàn Quốc về Việt Nam hôm nay

Mallela said...

Very informative content and intresting blog posts.Data science course in Nashik

Deekshitha said...

very informative blog
data science training in Pune

Mallela said...

Very informative content and intresting blog post.Data science course in Nashik

Deekshitha said...

very informative blog
data science training in Pune

Mallela said...

Very informative content and intresting blog post.Data science course in Thiruvananthapuram

Deekshitha said...

very informative blog
data analytics training in Pune

Mallela said...

Very informative content and intresting blog.Data science course in Thiruvananthapuram

Deekshitha said...

very informative blog
data analytics training in Pune

Mallela said...

Thanks for posting the best information and the blog is very informative.Data science course in Faridabad

Mallela said...

Thanks for posting the best information and the blog is very informative.Data science course in Faridabad

Deekshitha said...

very informative blog
data science training in Patna

ALAN COOPER said...

Compare Online coursework help to draw every person’s interest, Establish and clarify the exact arrangement or possessions of all homework. Insert articles linked to people. Grab the difficulties that come up in just how chosen subject. Illustrate how issues may be at the homework and offer a remedy to overcome all those issues. Find connections between those writers. Asses sing your own idea. All Assignment Help composing writing can possibly be an effective means to generate a fantastic mission.

Deekshitha said...

very informative blog
data science training in Patna

Mallela said...

Thanks for posting the best information and the blog is very informative.Data science course in Faridabad

Deekshitha said...

Informative blog
data analytics training in Patna

Deekshitha said...

Informative blog
data analytics training in Patna

Dipanshu Sharma said...

Thanks and keep posting such an informative blog.
Godrej Urban Park Chandivali Mumbai

Srigokul said...


Nice Blog. Thanks for Sharing this useful information...

Data science training in chennai
Data science course in chennai

Deekshitha said...

Informative blog
Business Analytics course in Mysuru

navya said...

It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions.
Biomedical engineering projects ideas

«Oldest ‹Older   201 – 236 of 236   Newer› Newest»