Annotated Java: Annotations in J2SE 5.0 Dave Landers BEA Systems, Inc
Annotated Java: Annotations in J2SE 5.0 Dave Landers BEA Systems, Inc
Agenda
Overview Annotations built in to J2SE 5.0 Defining Annotations Meta-Annotations Using Annotations
Reflection apt
Misc Topics
Simple Example
The annotation definition
@interface FixMe { String value(); }
The Usage
@FixMe( Missing method body ) public void theMethod() { }
Types
Class, Interface, Enum definition, Annotation Type
Method, Constructor, Field, Enum constant, Method parameter Local Variable declaration
Annotations are:
Modifiers, not documentation
Part of the code
Strongly typed
@interface
Well
@Override @Deprecated @SupressWarnings
@Deprecated
Like javadocs @deprecated
Without support for comments, replacement APIs
@Override Annotation
Very useful Asserts that you intend to override a method in a superclass Compiler will fail if not actually overriding
Without this would silently create method with new signature
Checks Override vs. Overload Checks for missing methods in base class
@Override example
class Base { void m(Type2 a, Type1 b) { } } class Sub extends Base { @Override void m(Type1 a, Type2 b) {} }
Sub.java:6: method does not override a method from its superclass @Override void m(Type1 a, Type2 b) ^
Kinds of Annotations
Marker annotations
Have no attributes @Override @Deprecated @Preliminary
Multi-valued annotations
@Review( reviewer=Landers, date=4/1/2004, comment=Close stream in finally block )
Defining Annotations
Defined as @interface Compile into java class files Automatically extends java.lang.annotation.Annotation
You dont write extends Annotation Extending Annotation does not make an annotation, only @interface marks an annotation
Annotation Definitions
@interface Review { String reviewer() default [unknown]; String date() default 0/0/00; String comment(); }
Usage
@Review( reviewer=Landers, comment=Does not say hello ) public void helloWorld() { }
Code Break
Example Annotation Definitions
SimpleAnnotations.java
Meta-Annotations
Annotations used when defining Annotations Specify how the Annotation can be used used
Defined in java.lang.annotation.* @Documented @Inherited @Target @Retention
Meta-Annotations
@Documented
Javadoc should be generated when this annotation is applied to an element Is the use of the annotation part of the public API?
@Inherited
Does the annotation get applied to subclasses or only to the base type? Only works on classes
Not overriden Methods Not Interfaces
@Target Meta-Annotation
Where the annotation can be used
What kind of source elements Default is all
public @interface Target { ElementType[] value(); } public enum ElementType { ANNOTATION_TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE }
TYPE
Class, Interface, Annotation, or enum
LOCAL_VARIABLE
Tools like apt cant currently access this
PARAMETER
Method parameter
PACKAGE
Package annotations go in package-info.java
@Target Usage
import static java.lang.annotation.ElementType.*;
@Target({TYPE, CONSTRUCTOR, PARAMETER}) public @interface Marker { } @Marker class Foo { // OK @Marker public Foo() { } // OK @Marker int x; // No @Marker public m( // No @Marker int param ) { // OK @Marker int variable; // No } }
@Retention Meta-Annotation
Where is the annotation retained
Where can the annotation be accessed and used Default is CLASS public @interface Retention { RetentionPolicy value(); } public enum RetentionPolicy { SOURCE, CLASS, RUNTIME };
Retention Policies
SOURCE
Discarded by the compiler
CLASS
Retained by compiler to class file, may be discarded by VM
RUNTIME
Retained in class file and by VM Can be accessed with reflection
@Retention Usage
@import java.lang.annotation.RetentionPolicy;
Code Break
Example Annotations and Meta-Annotations
@FixMe @ToDo Simple code using @FixMe and @ToDo
Accessing Annotations
Annotations are not much use unless you can access them and use them Where can we access Annotations?
Potentially any phase of
Develop Build Test Deploy Run
Compiler
javac recognizes java.lang.* annotations
@Deprecated, @Override, (@SuppressWarnings)
Deploy-time Processing
Container responding to runtime annotations ClassLoader accessing class-level annotations? Dynamic class generation, plug-ins, etc. Examples:
Dynamic generation of EJB descriptor information from annotated EJB ClassLoader generates BeanInfo class when annotated Bean is loaded
Code Break
Example using reflection
FixMeReporter NoBrokenCodeClassLoader
Limitations
No processing of local variable annotations
Using apt
Write an AnnotationProcessorFactory
That creates an AnnotationProcessor
Invoke apt
Much like javac Will compile any code generated by annotation processors
com.sun.mirror.declaration
Models representing declarations in the source
Field, Class, Method, etc.
com.sun.mirror.types
Models representing types in the source Usages (or invocations) of the declarations
com.sun.mirror.util
Utilities for processing declarations and types
AnnotationProcessorFactory
public Collection<String> supportedAnnotationTypes(); Return annotations supported by this Factory Can be com.foo.* or * public Collection<String> supportedOptions(); Return options recognized by this Factory
apt -Afoo -Abar=3
public AnnotationProcessor getProcessorFor( Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env ); Return an AnnotationProcessor for the types and environment described by the arguments
AnnotationProcessor
public void process();
Do something directly in this method Or use Visitors from com.sun.mirror.util.* Will usually use the environment from the AnnotationProcessorFactory
Iterate through Types being processed
@files
File(s) listing source files or other options
Apt Options
-classpath, -sourcepath, -d
Shared by apt and javac
-A[key[=val]]
Options passed to annotation processors
-s dir
Where processor-generated source files go
-factorypath path
Where to find annotation processor factories If used, classpath is not searched
-nocompile
Do not compile generated source
-factory classname
Annotation processor factory to use Bypasses default discovery process
-print
Do no processing or compilation, just print specified types
Code Break
Example using apt
CodeReportAPF LoggerAPF
Not mandatory
Annotation
@SupportedAnnotationTypes({FixMe,ToDo,Review}) class MyAP2 implements AnnotationProcessorFactory {}
Limitations
No inheritance of annotations
@interface
Limitations
No way to add simple behavior
@interface
Whats Missing?
More standard annotations - watch JSR-250
For J2SE things
Beans, GUI elements, etc.
Standard Annotations
JSRs for J2EE, EJB3, WebApp, Web Services, etc.
Generate all those required, boring, repetitive interfaces and descriptors from a single implementation class
Remote, Home, Local, etc. EJB interfaces, ejb-jar.xml Taglib TLD descriptor JAX-RPC interfaces, descriptors Web Services - JSR-181
Annotation Users
Cedrics TestNG
Mark test methods using Annotations, not name patterns Annotations to inject properties, etc.
Beehive
Annotation-driven programming model
Controls (Annotated JavaBeans) Web Services (JSR-181) NetUI: Struts, XMLBeans, Controls, JSF
More
Summary
Annotations are modifiers Annotations do not affect class semantics
Need build- or run-time tools, libraries for this
Cool Things
Annotations at runtime @Override apt
References
Suns Annotation overview
http://java.sun.com/j2se/1.5.0/docs/guide/language/ annotations.html
APT docs
http://java.sun.com/j2se/1.5.0/docs/guide/apt/ index.html
More References
Annotations in Tiger, Brett McLaughlin
http://www-106.ibm.com/developerworks/library/ j-annotate1
Beehive
http://incubator.apache.org/projects/beehive.html
TestNG
http://beust.com/testng/
Donald Smith
Caging the Tiger
Persistence, EJB3
The End
Please fill out the evaluations Example code available
On the conference CDROM http://boulderites.bea.com/~landers
References there, too