© 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.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Generic programming in Java
Java Annotations. Annotations  Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Abstract Classes and Interfaces.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Java 1.5 Annotations. Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
© 2006 by BEA Systems Inc; made available under the EPL v1.0 | March 2006 | Java Annotation Processing (APT) in the Eclipse JDT Gary Horen BEA Systems.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Java Implementation: Part 3 Software Construction Lecture 8.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Fun with Java Annotations Brian McGinnis. Java Annotations Introduced in “Tiger” release (Java 1.5) Introduced in “Tiger” release (Java 1.5) One of most.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Object Oriented Software Development
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Introduction to Generics
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
GoodOO Programming Practice in Java © Allan C. Milne v
Java 1 Introduction Why annotations?  Enhance ease-of-development  Shift some code generation from programmer to compiler What are annotations?
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Java Annotations. Annotations  Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Java Annotations for Types and Expressions Mathias Ricken October 24, 2008 COMP 617 Seminar.
Java Programming, Second Edition Chapter Twelve Advanced Inheritance Concepts.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 1 Chapter 15 Abstract Classes and Interfaces.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Lecture 5:Interfaces and Abstract Classes
Software Construction Lab 10 Unit Testing with JUnit
More on Java Generics Multiple Generic Types Bounded Generic Types
Enumerations & Annotations
Enumerations & Annotations
Java Programming Language
Packages and Interfaces
Generic programming in Java
Enumerations & Annotations
Java Programming Course
Java Programming Language
Presentation transcript:

© 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 1 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 2 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 Author { String name(); int year(); = “Walter Harley”, year = 2008) class MyClass {} declaration usage

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 3 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 4 Agenda Introduction How are annotations used? How do annotations fit into the language? What’s on the horizon? Q&A

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 5 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 editcompiledeployclassloadrun

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 6 Annotations as fancy comments Annotations as “standardized comments” – versus “/* don’t use this any more */”  Harder to mis-spell, easier to search, and less ambiguous. Defined entities in javadoc are pretty good; in javadoc fails silently. No programmatic access to the annotation implied in this case, it’s just there for humans to read. editcompiledeployclassloadrun

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 7 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 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 editcompiledeployclassloadrun

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 8 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 editcompiledeployclassloadrun

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v1.0 9 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 inserts transaction locking code around calls that need to be atomic. Other possibilities: load class differently depending on threading requirements, API version requirements, etc. editcompiledeployclassloadrun

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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 = IndexOutOfBoundsException.class) public void empty() { List l = new ArrayList (); l.get(0); // should throw exception }

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Reading annotations at runtime (Hibernate) Constraint validation in app server  Example: Hibernate data = 2, max = 50) public String getLastName () { return “”; // runtime exception! } editcompiledeployclassloadrun I’ll discuss how to read annotations at runtime after a bit of language background.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Agenda Introduction How are annotations used? How do annotations fit into the language? What’s on the horizon? Q&A

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Declaring a marker annotation type package 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 class MyClass {} declaration (MyAnno.java) usage (MyClass.java)

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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 Since { int major(); int minor() default 0; = 3, minor = 4) class MyClass {} declaration usage

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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 MaxLength { int value() default 80; } interface Foo String String getLastName(); } declaration usage

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Annotation types look like ScreenFormat { enum COLOR { RED, BLUE, GREEN, BLACK } COLOR background() default BLACK; static final int SCREEN_DPI = 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Annotation types can be used like MyAnno {}... class X implements MyAnno { // discouraged Class 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!

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v but with many MyAnno extends IFoo { int intVal(int x); Class 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Members can only be of certain types package MyAnno { String[] names(); Class 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v How do you annotate class public void x) {... 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Package annotations // file package p; // no other contents in file Example use case: deprecate an entire package 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Using an annotation: member // can’t pass null // ok to compute // can’t eval at runtime class 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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)

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Built-in class Y { public abstract int foo(); } class X extends Y List public int foo() {... } } Defined in java.lang; support built into the compiler or warns when deprecated item is turns off compiler warnings  There is no standard list of suppressible warnings warns if a method is not truly an override  avoid subtle errors, e.g., equals(MyClass f) vs. equals(Object o)  In Java applies only to methods in superclasses; in Java 6, implemented interface methods are also permitted.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Built-in annotations ElementType.FIELD, @interface MyAnno { does MyAnno get compiled into class file, and does it get loaded into the VM so it can be reflected on? Default is to which elements can MyAnno be will MyAnno be mentioned in javadoc of the classes it is present on? (Is it part of the API 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Reflecting on annotations at 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 Reflection is about the only way to create an in-memory instance of an annotation type (because annotations are interfaces).

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Agenda Introduction How are annotations used? How do annotations fit into the language? What’s on the horizon? Q&A

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v JSR-305: annotations for software quality IntelliJ and FindBugs already have annotations for performing certain flow 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 etc.  etc.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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  Throws clauses  Switch statements  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.

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v 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?

Java Annotations | © 2008 by BEA Systems Inc.; made available under the EPL v Agenda Introduction How are annotations used? How do annotations fit into the language? What’s on the horizon? Q&A Thanks for attending!

© 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