Java 1 Introduction Why annotations?  Enhance ease-of-development  Shift some code generation from programmer to compiler What are annotations?

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 6 Annotations Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Java Annotations. Annotations  Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
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++
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.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Introduction to Java CS 331. Introduction Present the syntax of Java Introduce the Java API Demonstrate how to build –stand-alone Java programs –Java.
Java 1.5 Annotations. Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
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.
Java Implementation: Part 3 Software Construction Lecture 8.
© 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.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
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.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
CIT 590 Intro to Programming First lecture on Java.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
GoodOO Programming Practice in Java © Allan C. Milne v
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.
Java Annotations for Types and Expressions Mathias Ricken October 24, 2008 COMP 617 Seminar.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
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.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
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.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
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
Enumerations & Annotations
Enumerations & Annotations
Java Programming Language
Interfaces.
Enumerations & Annotations
Java Programming Course
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Java Annotations.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Java

1 Introduction Why annotations?  Enhance ease-of-development  Shift some code generation from programmer to compiler What are annotations?  Meta-tags  Can be applied at various levels  Package  Classes  Methods 

2 Introduction Sun’s Definition:  "It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it." Annotations can direct program behaviors through:  Source code  Compiler  Runtime

3 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. Note difference between “annotation” and “annotation type.” Author { String name(); int year(); = “Brett Whiskers”, year = 2008) class MyClass {} declaration usage

4 Annotation Types package p; MyAnno {} Marker: No Elements, except the annotation name 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)

5 Annotation Types Single-Element: Provide a single value only MyAnnotation { String value(); (“What to do”) public void myMethod() {... } declaration usage

6 Annotation Types Multi-value: Provide multiple data members MyAnnotation { String doSomething(); int count; String date(); (doSomething=“What to do”, count=1, date=“ ”) public void myMethod() {... } declaration usage

7 Defining Annotation Type Annotation + interface + annotation name Annotation Type Methods  No parameters  No throws clauses  Return types  Primitives  String  Class  Enum  An annotation type  Array of the above types  May be declared with defaults MyAnnotation { String doSomething() default “nothing”; }

8 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 during compilation  Class file bytecode readers (BCEL)  Reflection at runtime editcompiledeployclassloadrun

9 Annotations as tags/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. Not only an effective human-readable marker, but compiler also generates warning when you use a deprecated item. editcompiledeployclassloadrun

10 Annotation processing at compile time Standard Annotations editcompiledeployclassloadrun

11 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) applies to methods in superclasses and implemented interface methods

public class Test_Deprecated public void doSomething() { System.out.println("Testing annotation name: 'Deprecated'"); } public class TestAnnotations { public static void main(String arg[]) throws Exception { new TestAnnotations(); } public TestAnnotations() { Test_Deprecated t2=new Test_Deprecated(); t2.doSomething(); // Generates warning }

public class Test_Deprecated public void doSomething() { System.out.println("Testing annotation name: 'Deprecated'"); } public class TestAnnotations { public static void main(String arg[]) throws Exception { new TestAnnotations().doSomeTestNow(); public void doSomeTestNow() { Test_Deprecated t2 = new Test_Deprecated(); t2.doSomething(); }

14 Processing annotations on class files Bytecode enhancement based on annotations  Libraries like BCEL to read and write class files Bytecode Engineering Example (Core Java, pp ) editcompiledeployclassloadrun

15 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 }

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

17 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

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

19 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

20 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)

21 Built-in annotations for ElementType.TYPE, 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 or fields 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.

22 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).

23 In-Class Example Annotating Event Handlers at runtime using Reflection