By Tori Wieldt on Jul 20, 2012
Metaprogramming is the secret behind the success of many Java frameworks such as Spring and Struts 2, and constitutes the backbone of many of the most fundamental APIs across the Java EE technology stack. More importantly, you can use metaprograming for improving your apps and app testing. In his session The Art of Metaprogramming in Java, presented at OSCON, Abdel Remani (@PolymaticCoder) explained the philosophy and theory behind metaprogramming, and then showed code examples illustrating the different mechanisms and techniques developers can use to take advantage of this underused feature of the Java programming language.
Remani started with an overview of metadata. Metadata is "data about data," for example, most people are familiar with HTML meta tags. Javadoc is also an example of metadata. The most common way to generate and display metadata in Java is using annotations. JSR 175 (A Metadata Facility for the Java Language) was introduced in Java SE 5.0, and it standardized how annotations are declared in Java code. JSR 250 introduced Common Annotations for the Java Platform. You can write your own java.lang.annotation package, just tell the Java compiler how the annotations are to be treated, including the element types to be annotated, retention policies, and default values.
Metaprogramming is writing programs that manipulate other programs or themselves based on metadata. One good use case is saving scanned metadata for use later during runtime, allowing for quicker startup of your application. Since there are no commonly defined best practices in the area of metadata, Remani calls this a "big boy's exercise." You can access metaprogramming at runtime via JSR 299, Pluggable Annotation Processing API. He recommends the following steps: 1) Define metadata, 2) Process metadata, 3) Construct a metamodel, and 4) Validate the metamodel.
Here are some of the libraries available to use for metadata processing:
Finally, Ramani introduced Project Averroes. His vision for the project is a metaprogramming framework that provides auto-discovery of annotations, annotation processing, metamodel construction and validation. "It is," he concluded, "a work in progress." Project Averroes is open source, and he welcomes comments and contributions.