an introduction to java annotations

35
© 2008 by BEA Systems Inc.; made available under the EPL v1.0 | 3/18/2008 | Java Annotations an introduction to Java Annotations Walter Harley BEA Systems Inc. @

Upload: alberto79

Post on 02-Dec-2014

113 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: An Introduction to Java Annotations

© 2008 by BEA Systems Inc.; made available under the EPL v1.0 | 3/18/2008 | Java Annotations

an introduction to

Java Annotations

Walter HarleyBEA Systems Inc.

@

Page 2: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.02

Introduction

•Who am I? Walter Harley, BEA Systems Inc. JDT APT lead; Eclipse committer since 2005 Caveat: I am not a J2EE developer

•I will be talking about: Use cases for annotations How to declare and use annotations SWAGs about the future of annotations

•I won’t be talking about: Details of writing annotation processors Annotation support features in Eclipse

@

Page 3: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.03

Quickly, what’s an annotation?

• Program metadata – decorations on ordinary Java code.

• Like javadoc comments, but with syntax and strong types.

• Meant to be both human- and machine-readable.

• No relation to Eclipse editor annotations!

@interface Author { String name(); int year();}

@Author(name = “Walter Harley”, year = 2008) class MyClass {}

declaration

usage

Page 4: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.04

Where did annotations come from?

•Main goal: auto-generate J2EE boilerplate code from metadata.

Another goal: better communication from developer to compiler, for optimization and error checking.

•Previously, generation was achieved via xdoclet or custom tools like ejbgen (v2.0), using javadoc comments as input.

•But programming in javadoc is unchecked and syntactically limited. Annotations are a solution.

•JSR-175 introduced annotations into Java 5, in 2004

Page 5: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.05

Agenda•Introduction

•How are annotations used?

•How do annotations fit into the language?

•What’s on the horizon?

•Q&A

Page 6: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.06

How are annotations used?

•There are use cases throughout the development cycle Capabilities and challenges different at each point

•Many ways to read, and act upon, an annotation Human-readable in source code Built-in support in IDE Annotation processing API (JSR-269) during compilation Class file bytecode readers (BCEL) Reflection at runtime

edit compile deploy classload run

Page 7: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.07

Annotations as fancy comments

•Annotations as “standardized comments” – e.g., @Deprecated, versus “/* don’t use this any more */”

Harder to mis-spell, easier to search, and less ambiguous.

•Defined entities (@deprecated) in javadoc are pretty good; but @depracated in javadoc fails silently.

•No programmatic access to the annotation implied in this case, it’s just there for humans to read.

edit compile deploy classload run

Page 8: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.08

Using annotations with IDE support

•Annotations let you tell the compiler/IDE what you mean, in more detail than the raw code will support.

•Integrity analysis (e.g., @NonNull in IntelliJ) Requires proprietary support built into the compiler/IDE

•Semantic error checking, e.g., only one method in an EntityBean should be a primary key.

May be implemented with an annotation processor

edit compile deploy classload run

Page 9: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.09

Annotation processing at compile time

•Generate additional Java types and artifacts (J2EE) RPC stubs, LocalHome interfaces, deployment descriptors

•Practical examples: EJB, JAX-WS

•Not well suited to composite files (message.properties, web-info.xml), because of incremental compilation

Can make composites in separate build step, or during deploy

edit compile deploy classload run

Page 10: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.010

Processing annotations on class files

•Bytecode enhancement based on annotations Libraries like BCEL to read and write class files

•Can modify existing class – which APT doesn’t let you do.

•Practical example: Resin app server @TransactionAttribute(REQUIRED) inserts transaction locking code

around calls that need to be atomic.

•Other possibilities: load class differently depending on threading requirements, API version requirements, etc.

edit compile deploy classload run

Page 11: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.011

Reading annotations at runtime (JUnit 4)

•JUnit 4 test runner finds annotated classes, instantiates them, executes the annotated methods

•Test case classes don’t need to subclass TestCase

edit compile deploy classload run

@Test(expected = IndexOutOfBoundsException.class)public void empty() { List l = new ArrayList<Object>(); l.get(0);  // should throw exception}

Page 12: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.012

Reading annotations at runtime (Hibernate)

•Constraint validation in app server Example: Hibernate data persistence framework

@NotEmpty@Length(min = 2, max = 50)public String getLastName () { return “”; // runtime exception! }

edit compile deploy classload run

I’ll discuss how to read annotations at runtime after a bit of language background.

Page 13: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.013

Agenda•Introduction

•How are annotations used?

•How do annotations fit into the language?

•What’s on the horizon?

•Q&A

Page 14: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.014

Declaring a marker annotation type

package p;

@interface MyAnno {}

• Declaration is like declaring a normal type. But notice the ‘@’ in the declaration

• A marker annotation is the simplest type of annotation

• No member values – just presence or absence of the annotation

import p.MyAnno;

@MyAnno class MyClass {}

declaration(MyAnno.java)

usage(MyClass.java

)

Page 15: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.015

Declaring a full annotation type

• A “full” or “normal” annotation is one with multiple members

• Again, a lot like declaring an interface, except... You can specify default values for members Lots of restrictions on members, which we’ll get to in a moment

• If all a full annotation’s members have defaults, it can be used like a marker annotation.

@interface Since { int major(); int minor() default 0;}

@Since(major = 3, minor = 4)class MyClass {}

declaration

usage

Page 16: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.016

Declaring a single-valued annotation type

• Only one member, named value.

• Can then omit the “value=” when using the annotation.

• The value member can have a default. Lets it be used like a marker annotation

@interface MaxLength { int value() default 80;}

interface Foo { @MaxLength(25) String getFirstName(); @MaxLength String getLastName();}

declaration

usage

Page 17: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.017

Annotation types look like interfaces...

@interface ScreenFormat { enum COLOR { RED, BLUE, GREEN, BLACK } COLOR background() default BLACK;

static final int SCREEN_DPI = 72; @interface VideoDevice { String name(); // name of device int dpi() default SCREEN_DPI; // resolution } VideoDevice[] supportedDevices();}

• Implicitly extend interface java.lang.annotation.Annotation defines equals(), hashCode(), toString(), and annotationType()

• Can declare constants, enums, and inner types.

• In bytecode, an annotation type is an interface, with a flag.

Page 18: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.018

Annotation types can be used like interfaces...

@interface MyAnno {}...class X implements MyAnno { // discouraged Class<? extends Annotation> annotationType() { MyAnno a = this; return a.getClass(); }}

• An ordinary class or interface can implement or extend an annotation type

• Variables can be of annotation type.

• Normally you’d only see this in code that was reflecting on annotations, not in the annotated code itself.

In practice, implementing an annotation type is unusual, and compilers may warn!

Page 19: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.019

...but with many restrictions

@interface MyAnno<T> extends IFoo { int intVal(int x); Class<T> type(); // Class<?> is okay String name() throws MyException;}

•Cannot be generic.

•Cannot explicitly extend any other interfaces.

•Methods cannot have any parameters

•Methods cannot have any type parameters

•Method declarations cannot have a throws clause

Intended use: passing around simple declarative metadata.

Page 20: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.020

Members can only be of certain types

package p;

@interface MyAnno { String[] names(); Class<? extends SomeType> type(); AnotherAnno[] nestedAnnos(); Object bean(); // not a legal member type}

• Primitive types (int, boolean, ...) and String• Class• enum• Annotation (but not the annotation being defined)• and one-dimensional arrays of the above.

Page 21: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.021

How do you annotate code?

@A class X { @A @B(“quux”) public void foo(@C x) { ... } @B private String s;}

• Syntactically, annotations are modifiers, like “final”.

• Annotations can be applied to any declaration: types (including enums and annotation types), fields, constructors, methods, parameters, enum constants, packages, and local variables.

Roughly speaking, the same things that you’d javadoc. JSR-308 seeks to extend the set of things that can be annotated.

• Can put multiple annotations on one element, but they must each be of a different annotation type.

Work around this with annotations that contain arrays of annotations

Page 22: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.022

Package annotations

// file package-info.java:@Deprecatedpackage p;// no other contents in file

• Example use case: deprecate an entire package with @Deprecated

• But packages usually have multiple declarations! By convention, annotate only one of them, in a file named “package-info.java”.

Analogous to package-info.html for javadoc Because this name contains a dash, it is not a legal identifier; so,

cannot contain a primary type.

• Package declaration comes before import statements, so must use qualified name for annotations from other packages.

Page 23: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.023

Using an annotation: member restrictions

@A(null) // can’t pass null value@B(3+4) // ok to compute constants@C(this.getClass()) // can’t eval at runtimeclass X {}

• Member values cannot be null (but can be an empty array or String)

• Values must be constant expressions I.e., computed statically at compile time

Page 24: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.024

Where do you get annotations?

•Write your own but non-standard annotations are of limited use, in practice,

because of the investment required to write tooling that uses them.

•Industry standards (org.apache, com.bea, …) Like APIs, annotations often start out proprietary and then

become standardized even if the implementation stays proprietary.

•Built into the Java language (java.lang)

Page 25: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.025

Built-in annotations@Deprecated class Y { public abstract int foo();}

class X extends Y { @SuppressWarnings(“unchecked”) List numbers; @Override public int foo() { ... }}

• Defined in java.lang; support built into the compiler or IDE.

• @Deprecated warns when deprecated item is used

• @SuppressWarnings turns off compiler warnings There is no standard list of suppressible warnings

• @Override warns if a method is not truly an override avoid subtle errors, e.g., equals(MyClass f) vs. equals(Object o) In Java 5, @Override applies only to methods in superclasses; in Java

6, implemented interface methods are also permitted.

Page 26: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.026

Built-in annotations for annotations

@Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.FIELD, ElementType.PARAMETER })@Documented@Inherited@interface MyAnno { }

• @Retention: does MyAnno get compiled into class file, and does it get loaded into the VM so it can be reflected on? Default is CLASS.

• @Target: to which elements can MyAnno be applied?

• @Documented: will MyAnno be mentioned in javadoc of the classes it is present on? (Is it part of the API contract?)

• @Inherited: if MyAnno is present on a class, is it inherited by subclasses?

The built-in meta-annotations control how the tools (compiler, javadoc, VM) will treat an annotation.

Page 27: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.027

Processing annotations at compile time

•APT: like xdoclet for annotations

•Annotation processors are modules that plug into a compiler API, and get called during compilation.

•Can report errors, and generate new types and resources Cannot change the existing code!

•Processors don’t see source code directly; instead, they see a “typesystem” – sort of like the Eclipse Java DOM.

No method bodies; just what the type looks like to other types

•Like reflection API, except introspecting on source code at compile time, rather than on live objects at runtime.

Page 28: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.028

The APT APIs

•Two distinct APT interfaces In Java 5, com.sun.mirror API, implemented by “apt” tool In Java 6, javax.annotation.processing API (JSR-269), directly

implemented by javac Eclipse 3.2 supports Java 5 interface; 3.3+ support both.

•Resource to learn more: APT tutorial presented at EclipseCon 2007, available online at eclipse.org.

•Warning: difficult API with many pitfalls and limitations

Page 29: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.029

Reflecting on annotations at runtime

@interface MaxLength { int value(); }

class ValidatingMethodCaller { String validate(java.lang.reflect.Method m, …) { MaxLength maxAnno = m.getAnnotation(MaxLength.class); String s = (String)m.invoke(…); if (maxAnno != null && s.length() > maxAnno.value() { throw new ValidationException(“exceeded max length”); } return s; }}

• Annotations have to explicitly be given @Retention(RUNTIME).

• Reflection is about the only way to create an in-memory instance of an annotation type (because annotations are interfaces).

Page 30: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.030

Agenda•Introduction

•How are annotations used?

•How do annotations fit into the language?

•What’s on the horizon?

•Q&A

Page 31: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.031

JSR-305: annotations for software quality

•IntelliJ and FindBugs already have annotations for performing certain flow analyses

@NotNull, @Nullable, @CheckForNull, @CheckReturnValue

•Currently these annotations are proprietary. Proposal is to standardize them so that the annotations, at least, can be shared across different tools.

Getting tools to support the annotations will be slower.

•Discussion also underway of annotations relating to concurrency; and a long tail of other issues more or less related to defect detection.

@ThreadSafe, @EventThreadOnly, etc. @Taint @Positive, @Nonpositive, etc.

Page 32: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.032

JSR-308: annotations in more places

•Declarations are the only thing that can be annotated, now.

•Proposal is to support annotations on many other elements Casts (@NonNull) Throws clauses (@Critical) Switch statements (@NoFallThrough) Array elements Type parameters Type bounds etc...

•Making use of such annotations, however, requires much deeper APIs for code inspection than we have now.

•Emphasis on compile-time checking; many of these constructs don’t even exist at runtime.

Page 33: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.033

SWAGs about the future

•Expect widespread use in J2EE: enterprise applications are the sweet spot for annotations

a lot of boilerplate code can leverage standards execute inside smart containers

•Expect increased support within development tools

•JSR 305 (software quality annotations) will gain broader support… slowly.

Implementations are proprietary, hard to leverage No plans yet in Eclipse?

Page 34: An Introduction to Java Annotations

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.034

Agenda•Introduction

•How are annotations used?

•How do annotations fit into the language?

•What’s on the horizon?

•Q&A

Thanks for attending!

Page 35: An Introduction to Java Annotations

© 2008 by BEA Systems Inc.; made available under the EPL v1.0 | 3/18/2008 | Java Annotations

an introduction to

Java Annotations

Walter HarleyBEA Systems Inc.

@