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.

75 comments:

Yeroc said...

Like the idea but would it not be better to extend the existing CDI @Stereotype annotation to work like this rather than introducing a new annotation?

Monster said...

Hi. This is quite interesting, but without a license, most devs (including me) would stay away from your code. Could you please add a license in the Github repo?

Kathiresan Muthu said...

Hi this is Kathiresan i am having 3 years of experience as a dot net developer and i am certified. i have knowledge on OOPS concepts in .NET but dont know indepth. After learning android will be enough to get a good career in IT with good package? and i crossed Android Training in Chennai website where someone please help me to identity the syllabus covers everything or not??

Thanks,
kathiresan

Kathiresan Muthu said...

Hi this is Kathiresan i am having 3 years of experience as a dot net developer and i am certified. i have knowledge on OOPS concepts in .NET but dont know indepth. After learning android will be enough to get a good career in IT with good package? and i crossed Android Training in Chennai website where someone please help me to identity the syllabus covers everything or not??

Thanks,
kathiresan

Victoria John said...

Thanks for sharing this informative blog.. If anyone want to get HTML Training in Chennai please visit FITA academy located at Chennai, Velachery. Rated as No.1 training and placement academy in Chennai.

rebeka christy said...

Your blog is really useful for me. Thanks for sharing this informative blog. If anyone wants to get real time Oracle Training in Chennai reach FITA located at Chennai. They give professional and job oriented training for all students.

Martina Christy said...

Your blog is really useful for me. Thanks for sharing this useful blog..Suppose if anyone interested to learn Android Training in Chennai please visit fita academy which offers best Android Course in Chennai at reasonable cost.

Jenny Peter said...

Nice explanation .Its really superb.
Software Testing Training in Chennai | QTP Training in Chennai | Selenium Training in Chennai

christ evert said...

hi i hope to hadoop training in chennai |hadoop training chennai
really understand for this sites..hadoop training in chennai | hadoop training chennai

christ evert said...

hi,we have to posted for awesome information..hadoop training in chennai | hadoop training chennai

gopi best said...

Hi, i have to read for your full sites information oracle dba training in chennai very good information you having for sharing..Thanks a lot...oracle dba training in chennai

maxwell anderson said...

hi, i see that for your wonderful information..oracle dba training in chennaiAlso i am told him very good information you have for sharing Thank for that...oracle dba training in chennai

maxwell anderson said...

hi, i have to learning for lot informarion..oracle training in chennai
i need for learnin more this sites..oracle training in chennai

maxwell anderson said...

hi, very nice informative..oracle training in chennai | oracle training in chennai

glennparyy said...

Java training in Chennai

Stereotype is based fully on annotation Android training in chennai So we can easily bring up a full file IOS training in chennai

jessycharl said...

Java training in Chennai

Hi dude Android training in chennai Just we are in coding scripts IOS training in chennai Shall we describe it Android training in chennai

Jessycharl said...

Java training in Chennai

May this complement help others to mingle it Android training in chennai But later we got into main format regarding superficial ethics Java training in Chennai

Success Best said...

I have joined the oracle Trained in Training in Bangalore. Oracle Trainer will be teaching in practically Manner. So I can Easily able to understand the any Concept. This is very helpful for the interviews Purpose . I would refer my frnds to joined this institute. Visit Us, Oracle Training in Bangalore

Jenny Peter said...

Meta annotaqtion is new topic and its really helpful..Thanks.
Software Testing Training in Chennai | QTP Training in Chennai | Selenium Training in Chennai | Loadrunner Testing Training in Chennai

rebeka christy said...

Salesforce Training

The information you posted here is useful to make my career better keep updates..I did Salesforce Training in Chennai at FITA academy. Its really useful for me to make bright future in IT industry.

Salesforce CRM Training in Chennai | Salesforce Admin Training in Chennai | Salesforce.com Training in Chennai | Sales Cloud Consultant Training in Chennai

fathima m said...

welcome admin, hadoop training in chennai thanks a lot..i may need to truly perceive for oracle training in chennai this information..oracle dba training in chennai .So,We need to giving unmistakable information.i need to look at for this regions informarion..Awesome message..

fathima m said...

Since we have made the new tech to imagine the oracle training in chennai costs yet it directs a tad bit of concordant.Thank you so much.. oracle training in chennai .i may need to really see for this information..So,We need to giving unmistakable information.i need to take a oracle dba training in chennai gander at for this locales informarion..

joyce christopher said...
This comment has been removed by the author.
joyce christopher said...

Nice to blog. i have takeup training with in 2 months in besanttechnology at chennai. training session going on very well.Php training in chennai | oracle training in chennai | Oracle- dba- training in chennai

mathew delport said...

Thanks for your informative article. As the demand quality apps and games increases in the mobile market, there is huge demand for the android developers in the job market. It is recommended to go for Android training to boost his/her career prospects.

Victoria John said...

Java is one of the popular technologies with improved job opportunity for hopeful professionals. Java Training in Velachery helps you to study this technology in details.If you are looking for best Java Institutes in Chennai reach Fita academy.

dhanamlakshmi palu said...

Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Android Training in chennai | Android Training chennai | Android course in chennai | Android course chennai

john son said...

Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Course in Chennai reach FITA, rated as No.1 Dot Net Training Institutes in Chennai.

dhanalakshmi palu said...
This comment has been removed by the author.
dhanalakshmi palu said...

Your posts is really helpful for me.Thanks for your wonderful post. I am very happy to read your post. cloud computing training in chennai | cloud computing training chennai | cloud computing course in chennai | cloud computing course chennai

RS Trainings said...

Thanks for this valuable information.Oracle DBA Online Training is Useful for the Oracle developers.For more details Oracle DBA Training

Emi Jackson said...

Hi, This is Emi from Chennai. I have read your blog and I got some knowledge information. Really useful blog. Keep update your blog.

Regards...
Java Training Center in Chennai

stellen john said...

Very helpful to information sharing . now i completed my course java at chennai. please visited us@ Java Training Chennai

murali karthik said...

Excellent post!!! In this competitive market, customer relationship management plays a significant role in determining a business success. That too, cloud based CRM product offer more flexibility to business owners to main strong relationship with the consumers. Salesforce Training Institutes in Chennai | Salesforce Training in Chennai

Sathik Ali. A said...

Thanks for sharing the useful information. Excellent blog with many useful information about Mobile Apps Development. I am planning to do Android Training in Chennai and kindly please suggest me is the best place for Android Training . If any other iOS Training Institute in Chennai is their please let me know. Thanks for blog and thanks for reply guys.

Jamuna Pandy said...

Hi friends, This is Jamuna from Chennai. I am a technology freak. I have read your blog and got some valuable information from this blog. Your technical information is really useful for me. Keep update your blog.
Regards..
Oracle Training




kovalan Jayamurugan said...

Informative article!!! Being flagship too for Microsoft, Asp.Net is loaded with various essential tools that allow developers to build robust web applications. PHP Training

rebeka christy said...

Hi, I wish to be a regular contributor of your blog. I have read your blog. Your information is really useful for beginner. I did Software Testing Training in Chennai at Fita training and placement academy which offer best QTP Training in Chennai with years of experienced professionals. This is really useful for me to make a bright career.

john son said...

Thanks for sharing your innovative ideas..Its really useful and interesting...

Regards...

Salesforce Developer Training in Chennai

Victoria John said...

Thank you so much for sharing this informative blog. Your technical information is really useful for me. Keep update your blog.

Regards..

PHP Training Chennai

Emi Jackson said...

Your blog is really awesome and I got some useful information from your blog. This is really useful for me. Thanks for sharing such a informative blog. Keep posting.

Regards..
Cloud Computing Training in Chennai

raju kr said...

EMTV is Papua New Guinea’s Best Article news provider in countries. This channel is one of the most trusted sources of PNG news, PNG Local news, PNG Videos, PNG news Article & many more.

Papua New Guinea News

Martina Christy said...

Hi, Your blog is really very informative and useful for me. Thanks for sharing this valuable blog.
Regards..
Unix Training

Rafiq Abdul said...

Very...very useful Blog.Thanks for sharing
informatica training in chennai adyar with placement

Sathiya Narayanan said...

Thanks for sharing your innovative and useful ideas..i like your blog regards.
Get more ideas on peridotsystem by visiting:

<a href="http://www.peridotsystem.in/in chennai adyar with placement</a>

Roshini RS said...

Thanks for sharing; Salesforce crm cloud application provides special cloud computing tools for your client management problems. It’s a fresh technology in IT industries for the business management.
Regards,
Salesforce training in Chennai|Salesforce training institute in Chennai

Jennifer M said...

thanks for sharing your information. we are providing sap mm training in our institute. visit our website if you want to know the details of SAP.

best SAP ABAP training in chennai

Lucy H said...

Learn Linux Training in Chennai with Experts. We are Best Linux Training

Institute in Chennai. We are covering RHCE Linux Training from Beginner to

Advanced
Linux Server Training

in chennai

Lucy H said...

thanks for your knowledge share best data warehouse training in chennai
http://www.thinkittraining.in/bi-data-warehousing-training

Badrul Jaman said...

Excellent information ... for Objective-C Training in Chennai

Lakshmi said...

Vmware troubleshooting Training in chennai with placement. We plan the courses according to the current requirements to educate them in both theoretical and practical way.
view more:
http://www.vmwaretraining-chennai.in/vmware-troubleshooting.html

Lakshmi said...

Linux Training in chennai. we offered how use linux os , linux server training and training method both theory and practical way to teach.
view more:
http://www.linux-trainingchennai.in/corporate-training.html

peridot systems said...

Informatica Training in Chennai with real-time corporate professionals. We are providing practical oriented best Informatica training institute in Chennai
<a href="http://www.oraclesqltraining.in/home.html></a>

peridot systems said...

Learn Android, iOS training in Chennai. We offers Best Mobile Applications Training in Chennai.

Learn any Mobile Applications Training with us in Chennai
IOS training Institutes in

Chennai

jhansi joe said...
This comment has been removed by the author.
jhansi joe said...

This technical post helps me to improve my skills set, thanks for this wonder article I expect your upcoming blog, so keep sharing..
Regards,
Salesforce course in Chennai|Salesforce training chennai

Lily D said...

Excellent linux server institute in chennai with 100% placement with realtime IT legends with feasible fee .
We are covering Redhat Linux Training from Beginner to Advanced.
Linux Server Training in chennai

Lily D said...

Best VMWare Training in Chennai provided by Certified Professionals. We are the Best VMWare Training Institute in Chennai. Best VMWare Coaching Center Adyar
VMWare Training in Chennai

Lily D said...


IOS Training in Chennai provided by Certified Professionals. We are the Best IOS Training Institute in Chennai. Best IOS Coaching Center Adyar
IOS training Institutes in Chennai

peridot systems said...

Learn Cloud Computing training in Chennai with Placement. We offers Best Cloud Computing Training in Chennai
<a href="http://www.peridotsystems.in/salesforce-cloud-consultant-training-in-chennai.php>SalesForce Training in Chennai </a>

peridot systems said...



VMWare Vcloud Training in Chennai provided by Certified Professionals. We are the

Best VMWare Vcloud Training Institute in Chennai. Best VMWare Coaching Center

Adyar

www.vmwaretraining-chennai.in

peridot systems said...

We are the no.1 MSBI Training Institute providing MSBI Training in Chennai with 100% job placement by experienced Data Integration experts
<a href="http://msbitraining-chennai.in/module2.html>SSRS Training in Chennai</a>

peridot systems said...

We are the best IT training and placement institute in Chennai with training center in Adyar. Join us for IT training and placement
<a href="http://www.androidtraining-chennai.in/android-training-chennai.html>Android Training</a>

peridot systems said...

Meta annotations annotate an annotation. That is, annotation for another annotation. Following is the list.

1. @Retention
2. @Target
3. @Documented
4. @Inherited

java Training in Chennai

peridot systems said...

Spring 4 Meta Annotations Spring

META ANNOTATIONS DEFINED
CREATING COMPOSED ANNOTATIONS
ANNOTATION ATTRIBUTES--->@Repository("myOrderDao")
WRAP UP

Best Java Training in Chennai

peridot systems said...

Annotation Type:

@interface {
method declaration;
}

Meta Annotations:

@Target(ElementType.METHOD)
public @interface MethodInfo { }

Java Training institute in chennai

peridot systems said...

public @interface TestAnnotation
{
// Property Definition here.
}
- J2EE Training in Chennai

peridot systems said...

Java Annotations are also called Metadata. Annotations are introduced with JDK 5 onwards. Annotations allows us to add some form of metadata information into our source code, but it doesnot change the execution flow of the program. These annotations can then be processed at compile time by the compiler tools or during at runtime via Java Reflection. Classes, methods, variables may be annotated.

Best JAVA Training in Chennai

Narender Godara said...

Packers and movers Bareilly
Packers and movers Bathinda
Packers and movers Bhopal
Packers and movers Bhubaneswar

Stephen said...

There are lots of information about latest technology and how to get trained in them, like Hadoop Training Chennai have spread around the web, but this is a unique one according to me. The strategy you have updated here will make me to get trained in future technologies(Hadoop Training in Chennai). By the way you are running a great blog. Thanks for sharing this. FITA chennai reviews

sss said...

thanks for this wonder article.Informatica is such a course that requires learning the technological features of the product. visit our site for more details informatica online training in hyderabad

Regina Rj said...

This technical post helps me to improve my skills set, thanks for this wonder article I expect your upcoming blog, so keep sharing..
Php Course in chennai

sss lokesh said...

meta annotations , xml concepts are very use full ... excellent posts....

R u looking for the best salesforce traingin institute in hyderabad.... This is not only best for training .. for job's also... feel free to contact us to know more about the technology & the openings ....

Salesforce Training In Hyderabad

kovalan Jayamurugan said...

Thanks for your informative article on cloud technology. Salesforce Training in Chennai

kovalan Jayamurugan said...

Thanks for your informative article. Your blog is loaded with awesome information. Please include RSS field shat that we can receive your latest post direct to my inbox. Wordpress Course in Chennai