Using Java Annotations in Eclipse Gary Horen BEA

Using Java Annotations in Eclipse Gary Horen BEA Systems Tim Wagner BEA Systems Copyright BEA 2005, made available under EPL 1. 0 | 1

Agenda Background Simple Example Demo Mirror API and APT Pitfalls More Elaborate Example Futures 2

What are annotations? Metadata placed directly in your source code Standardized by JSR 175, added to Java in 1. 5 Intended to replace “xdoclet”-style programming with a modern, type-checked equivalent @My. Annotation(num=5, str=“hi”) public class Foo { … } 3

What are annotations? Defined using Java – much like interfaces Can be used by both tools and runtimes Enable a simpler “POJO”-based programming model public @interface My. Annotation { int num; String str; } 4

What can an annotation do? Example: helping a POJO to become a web service Annotations on user code generate helper objects Endpoint interface: receives and parses XML message Bindings embody the message as parameters to the POJO method @Webservice Public class Foo { generates Endpoint Interface XML-Java Bindings } 5

Who uses annotations? J 2 SE – builtin annotations J 2 EE – EBJ 3. 0, JSR 181, JSR 250, JAXB 2. 0, JAX-WS 2. 0 3 rd party frameworks: Hibernate, Beehive, Spring …and eventually every major IT organization @Deprecated @Web. Service @Persistent @My. Corporate. Annotation 6

Build-time uses Many annotations effects happen at build time, not run time “I need to create a stub/skeleton that matches this interface” “I need to inform my container that I need resource X” “I need to verify that this method meets some constraints” We need several things to make this useful Something to process a set of annotations – an annotation processor A build (compile) time container for these processors – a compiler with extra smarts Enhanced visual tools – make Eclipse aware of the special semantics of annotations 7

Process view Processor Container Annotated Source File @My. Anno public class Foo {. . . } apt tool in JDK 1. 5 or compiles Eclipse apt plugin calls @My. Anno processor 8 another processor

What can an annotation processor do? Can Claim a set of annotations Check annotations for semantic errors Generate new Java source files Generate arbitrary data files (e. g. deployment descriptor) Cannot Change the bytecode generated when the file is compiled in any way 9

Demo. Annotation An Annotation contains elements Elements contain names and values An annotation processor can check element values for correctness Type. Generating. Annotation Generates a Java source file 10

Demo: processor finds invalid value 11

Demo: annotation generates type 12

Agenda Background Simple Example Demo The mirror API and APT Pitfalls More Elaborate Example Futures 13

What you need to provide Step 1: Locate or write your own annotation(s) public @interface My. Annotation { int num; String str; } 14

What you need to provide Step 2: Write an annotation processor factory import com. sun. mirror. apt. *; public class My. Annotation. Factory implements Annotation. Processor. Factory { Annotation. Processor get. Processor. For() … } 15

What you need to provide Step 3: Write an annotation processor import com. sun. mirror. apt. *; public class My. Annotation. Processor implements Annotation. Processor { void process() } 16

Packaging You provide The annotation declaration An implementation of Annotation. Processor. Factory An implementation of Annotation. Processor These are packaged in a jar Processor runs inside a dispatching framework Command line APT org. eclipse. jdt. apt. core plugin 17

Environment APIs Annotation Processor Environment @Foo @Bar a @Baz. . . b Declarations to process Type system exploration d c File generation 18 Error messages

Using Annotation. Processor. Environment get. Declarations. With(annotation) Declaration get. Annotation. Mirrors() Annotation. Mirror get. Element. Values() Element map 19

Processing rounds Round 1: Original source files Round 2: Types generated by processing original files in round 1 Round 3: Types generated in round 2 20

“Write once” – processor reuse apt tool in JDK 1. 5 or Eclipse apt plugin apt tool in JDK 1. 5 @My. Anno processor 21

Dispatching: command line support apt Tool available in JDK 1. 5 (along with javac, javadoc, javap, etc. ) Works like javac, but with something extra: It runs 3 rd party annotation processors in addition to compiling source code Any generated types also get compiled Locates factories through META-INF/services/ com. sun. mirror. apt. Annotation. Processor. Factory file: Each line of file = fully qualified factory class name % apt –classpath Proc. jar My. Program. java 22

Dispatching: inside Eclipse From a jar file external to the workspace Classpath variables provide indirection From a jar file inside a project Static jar only: jar file may not be rebuilt in same workspace that uses it Jar file must be available on the Eclipse Java compiler runtime classpath From a plugin <extension point=org. eclipse. jdt. apt. core. annotation. Processor. Factory> Debugging must be done in plugin: Build in development workspace Run on annotated source in debugged workspace 23

Eclipse APT configuration UI 24

Agenda Background Simple Example Demo The mirror API and APT Pitfalls More Elaborate Example Futures 25

Pitfall: APT round implemenation All of round 1 runs first Round 1 @Foo class Quack @Roo class Mumble @Goo class Moo @Bar class Gen. Mumble @Bar class Gen. Moo Then all of round 2 Round 2 @Bar class Gen. Quack 26

Pitfall: Eclipse round implementation Dispatch all this Then this Round 1 @Foo class Quack @Roo class Mumble @Goo class Moo Round 2 @Bar class Gen. Quack @Bar class Gen. Mumble @Bar class Gen. Moo Rounding in Eclipse must be file-at-a-time for performance reasons. 27

Pitfall: gathering generated files @Foo class Quack Round 1 generates Round 2 reads all @Roo class Mumble Roo. xml Foo. xml @Goo class Moo Goo. xml @Bar class Gen. X Don’t do this. It depends on dispatcher implementation. Instead: gather generated files in a post-build step. 28

Pitfall: processor requests generated type Round 1 generates Round 2 generates @Goo class Moo @Foo class Quack @Bar class Gen. Foo class Gen. Goo Anno processor requests: not OK class Gen. Bar Generated type refers to: OK Don’t do this. It depends on visibility of generated types. But: generated types can refer to other generated types. 29

Pitfall: APT round implemenation All of round 1 runs first Round 1 @Foo class Quack @Roo class Mumble @Goo class Moo @Bar class Gen. Mumble @Bar class Gen. Moo Then all of round 2 Round 2 @Bar class Gen. Quack 30

Pitfall: build vs. reconcile Interactive (as you type) compilation = reconcile Can’t put new files on disk File generation happens only during build Best practice: build your workspace before you edit Then reconcile can see generated types Less confusion for the user Set project autobuild (build on Save) to “on” Keep build current Hopefully reconcile limitation goes away in next release 31

Agenda Background Simple Example Demo The Mirror API and APT Pitfalls More Elaborate Example Futures 32

Example: the Chargeable annotation App developer annotates a class to use the accounting system: Class level annotation: @Chargeable Method level annotations: @Charge. Per. Call(amount = 0. 003) @Charge. Wall. Clock. Time @No. Charge 33

What does @Chargeable do? Generates wrapper class with proxy method that posts charge Generates ISome. Service interface; both wrapper and app class implement Generates factory that creates the wrapped Some. Service class Some. Service. Wrapper private Some. Service _service; public execute. Request() start = current. Time. Millis(); _service. execute. Request(); Account. System. charge( current. Time. Millis() – start); 34 class Some. Service @Charge. Wall. Clock execute. Request()

Code Snippet: using @Chargeable public class Analysis. Service { @Charge. Wall. Clock. Time public Result. Set execute. Query(String key) { … } @Charge. Per. Call(amount =. 007) public int find. Median. Salary(Result. Set res) { … } @No. Charge public int find. Mean. Sales(Result. Set res) { … } 35

@Chargeable generates source files Generated source User’s code 36

Agenda Background Simple Example Demo The Mirror API and APT Pitfalls More Elaborate Example Futures JSR 269 UI Enhancements 37

JSR 269 Annotations already standard language feature (JSR 175) Standard annotations exist for specific applications (JSR 181, 220) The mirror API is a preview interface (com. sun. mirror) Sun has announced intention to open-source interfaces JSR 269 will standardize the processor API (in javax package space) Specification will wrap up soon, to be available in Java SE 6 Target Eclipse availablity: 3. 2 Mirror support continues in Eclipse until 269 widely adopted 38

User Interface APIs Eclipse apt plugin @My. Anno processor factory 39

Eclipse-specific functionality Code assistance inside annotation values Auto-completion Quick-fix Visual editing A special viewer/editor for annotations Refactoring Participation in rename operations Find-uses 40

Code assistance: auto-completion User presses Ctrl-space Annotation processor proposes content 41

Code assistance: quick-fix Annotation processor posts an error or warning User presses Ctrl-1 Annotation processor can propose fixes to the user 42

Visual Annotation Editor Show complex annotations in friendlier way Property pane-like UI Values in code in bold typeface Defaulted values in normal typeface Make nested annotations understandable @My. Service( buffer = @Message. Buffer(enable = true), conversation = @Phase(“start”) ) public boolean test. Verify. Funds(Mumble m) { … } 43

Release Timeline: APT in Eclipse JUN JUL AUG 3. 1 SEP OCT NOV DEC JAN FEB MAR APR JUN 3. 2 3. 1. 1 Alpha (core) Beta (UI Features) APT released as part of JDT 44

Q&A Try it out! Download and install at: http: //www. eclipse. org/jdt/apt/intro. To. APT. html 45

Using Java Annotations in Eclipse Gary Horen BEA Systems Tim Wagner BEA Systems Copyright BEA 2005, made available under EPL 1. 0 | 46
- Slides: 46