Java 1.5 Annotations. Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

Lecture 6 Annotations Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
The Java Programming Language
Java tools Java programming ID Sep javac – Java compiler Java source code files: *.java Java byte code files: *.class Java resource archives:
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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++
Outline Java program structure Basic program elements
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Java Language and SW Dev’t
Test Automation For Web-Based Applications Portnov Computer School Presenter: Ellie Skobel.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Effective Java: Generics Last Updated: Spring 2009.
The Java Programming Language
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.
Intro and Review Welcome to Java. Introduction Java application programming Use tools from the JDK to compile and run programs. Videos at
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
JAVA BASICS Prepared by The Smartpath Information Systems
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Software Documentation Section 5.5 ALBING’s Section JIA’s Appendix B JIA’s.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
Java 1 Introduction Why annotations?  Enhance ease-of-development  Shift some code generation from programmer to compiler What are annotations?
1 Java Programming II Annotations and Reflection.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 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.
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.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Execution ways of program References: www. en.wikipedia.org/wiki/Integrated_development_environment  You can execute or run a simple java program with.
Annotation trước tiên được hiểu là một dạng meta data. Meta data là đặc tả dữ liệu cho một đối tượng, giá trị gì đó. VD: các tập tin mp3, ảnh, hoặc một.
Chapter 9 Introduction to Arrays Fundamentals of Java.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
Sun Tech Talk 2 Java 1.5 and NetBeans 5.0 Pierre de Filippis Sun Campus Evangelist
Variable Scope & Lifetime
The need for Programming Languages
Software Construction Lab 10 Unit Testing with JUnit
Working with Java.
Chapter 9 Inheritance and Polymorphism
Enumerations & Annotations
Enumerations & Annotations
Java Programming Language
Enumerations & Annotations
Java Programming Course
CS520 Web Programming Java Annotations
Java Annotations.
Presentation transcript:

Java 1.5 Annotations

Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine revisions; sometimes they are orthogonal to, or outside of, the purposes of the language The preference is to not rewrite the compiler One of the new ease-of-development features in Java 5 are annotations

Previous Examples The Java platform has always had various ad hoc annotation mechanisms Javadoc annotations /** * Locate a value in a * collection. value the sought-after value the index location of the value NotFoundException */ int search( Object value ) { - an ad hoc annotation indicating that a field should be ignored by the serialization - an ad hoc annotation indicating that the method should no longer be used

Introduction Annotations provide data about a program that is not part of the program itself. An annotation is an attribute of a program element. As of release 5.0, the platform has a general purpose annotation (metadata) facility that permits to define and use your own annotation types. The facility consists of: a syntax for declaring annotation types a syntax for annotating declarations APIs for reading annotations a class file representation for annotations an annotation processing tool

Usage Annotations have a number of uses, among them: Information for the compiler - Annotations can be used by the compiler to detect errors or suppress warnings Compiler-time and deployment-time processing - Software tools can process annotation information to generate code, XML files, and so forth Runtime processing - Some annotations are available to be examined at runtime (reflection)

Annotation Type Declaration [1/2] Similar to normal interface declarations: An precedes the interface keyword Each method declaration defines an element of the annotation type Methods can have default values Once an annotation type is defined, you can use it to annotate declarations RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; }

Annotation Type Declaration [2/2] Method declarations should not have any parameters Method declarations should not have any throws clauses Return types of the method should be one of the following: primitives, String, Class, enum, array of the above types RequestForEnhancement { int id(); String synopsis(); String engineer() default "[unassigned]"; String date(); default "[unimplemented]"; }

Annotating Declarations [1/2] Syntactically, the annotation is placed in front of the program element's declaration, similar to static or final or protected An annotation instance consists of the " sign the annotation name a parenthesized list of name-value id = , synopsis = "Enable time-travel", engineer = "Mr. Peabody", date = "4/1/3007" ) public static void travelThroughTime(Date destination) {... }

Annotating Declarations [2/2] In annotations with a single element, the element should be named value : It is permissible to omit the element name and equals sign (=) in a single-element annotation: If no values, then no parentheses needed: Preliminary { public class TimeTravel {... } Copyright { String value(); Yoyodyne Propulsion Systems") public class OscillationOverthruster {... }

What can be annotated? Annotatable program elements: package class, including interface enum method field only at compile time local variable formal parameter

Annotations Used by the Compiler There are three annotation types that are predefined by the language specification - indicates that the marked element is deprecated and should no longer be - informs the compiler that the element is meant to override an element declared in a - tells the compiler to suppress specific warnings that it would otherwise generate

Meta-Annotations Meta-annotations - types designed for annotating annotation-type declarations (annotations-of-annotations) - indicates the targeted elements of a class in which the annotation type will be applicable TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, - how long the element holds onto its annotation SOURCE, CLASS, - indicates that an annotation with this type should be documented by the javadoc - indicates that the annotated class with this type is automatically inherited

Annotation Processing It's possible to read a Java program and take actions based on its annotations To make annotation information available at runtime, the annotation type itself must be annotated : Annotation data can be examined using reflection mechanism, see e.g. java.lang.reflect.AccessibleObject : T getAnnotation(Class ) Annotation[] getAnnotations() boolean AnnotationForRuntime { // Elements that give information for runtime processing }

Bigger Example The following example shows a program that pokes at classes to see "if they illustrate anything" Things to note in example: An annotation may be annotated with itself How annotations meta-annotated with Retention(RUNTIME) can be accessed via reflection mechanisms

Class { Illustrate.Feature.annotation, Illustrate.Feature.enumeration } ) Illustrate { enum Feature { annotation, enumeration, forLoop, generics, autoboxing, public String toString() { return "the " + name() + " feature"; } }; Feature[] value() default {Feature.annotation}; }

import {Illustrate.Feature.enumeration,Illustrate.Feature.forLoop}) public class Suggester // not yet supported public static void main( String[] args ) { try { java.util.Scanner userInput = new java.util.Scanner( System.in ); System.out.print( "In what class are you interested? " ); Class theClass = Class.forName( userInput.next() ); Illustrate ill = (Illustrate)theClass.getAnnotation( Illustrate.class ); … continued …

if ( ill != null ) { System.out.println( "Look at this class if you'd " + " like to see examples of" ); for ( Illustrate.Feature f : ill.value() ) { System.out.println( "\t" + f ); } else { System.out.println( "That class will teach you nothing." ); } catch( ClassNotFoundException cnfe ) { System.err.println( "I could not find a class named \"" + cnfe.getMessage() + "\"." ); System.err.println( "Are you sure about that name?" ); }

$ javac *.java Note: Suggester.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. $ java Suggester In what class are you interested? Suggester Look at this class if you'd like to see examples of the enumeration feature the forLoop feature $ java Suggester In what class are you interested? Illustrate Look at this class if you'd like to see examples of the annotation feature the enumeration feature Compilation and Execution

$ java Suggester In what class are you interested? Coin That class will teach you nothing. $ java Suggester In what class are you interested? Foo I could not find a class named "Foo". Are you sure about that name? More Execution

Example – JPA Annotations When using JPA, you can configure the JPA behavior of your entities using - designate a plain old Java object (POJO) class as an entity so that you can use it with – database – – inheritance controlling

Example – JUnit Annotations Annotations and support for Java 5 are key new features of JUnit – annotates – annotates setUp() and tearDown() methods for – class-scoped setUp() and – do not run test

Conclusions Java annotations are a welcome unification and standardization of approaches to annotating code that language designers and implementors have been doing for decades Annotations do not directly affect the semantics of a program It is not hard to learn!

References Sun Annotations Guide uage/annotations.html Java Annotations Tutorial avaOO/annotations.html An Introduction to Java Annotations p/ p/