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.

Slides:



Advertisements
Similar presentations
J0 1 Marco Ronchetti - Web architectures – Laurea Specialistica in Informatica – Università di Trento Java XML parsing.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
Generics and The ArrayList Class
For use of Cleveland State's IST410 Students only 1 Exception.
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.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
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.
Alice in Action with Java
Java 1.5 Annotations. Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Programming Languages and Paradigms Object-Oriented Programming.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Java Generics.
© 2006 IBM Corporation IBM WebSphere Portlet Factory Architecture.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Copyright © Curt Hill Java Looking at our first console application in Eclipse.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Question of the Day  On a game show you’re given the choice of three doors: Behind one door is a car; behind the others, goats. After you pick a door,
Javadoc: Advanced Features & Limitations Presented By: Wes Toland.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Introduction to Generics
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.
Java 3: Odds & Ends Advanced Programming Techniques.
M1G Introduction to Programming 2 5. Completing the program.
Attributes C#.Net Software Development Version 1.0.
Java 1 Introduction Why annotations?  Enhance ease-of-development  Shift some code generation from programmer to compiler What are annotations?
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
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.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Java Annotations. Annotations  Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
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.
OOP Basics Classes & Methods (c) IDMS/SQL News
Execution ways of program References: www. en.wikipedia.org/wiki/Integrated_development_environment  You can execute or run a simple java program with.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
Java Generics.
More on Java Generics Multiple Generic Types Bounded Generic Types
Enumerations & Annotations
Enumerations & Annotations
Java Programming Language
Inheritance Inheritance is a fundamental Object Oriented concept
Enumerations & Annotations
Java Programming Course
Review: libraries and packages
Java Annotations.
Presentation transcript:

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 interesting Java extension in a long time One of most interesting Java extension in a long time Ability to declare metadata modifiers for Java language upon: Ability to declare metadata modifiers for Java language upon: Type declarations, Constructors, methods, Members, Parameters, Variables Type declarations, Constructors, methods, Members, Parameters, Variables

Standard Java 1.5 Annotations Tiger has some useful built-in annotations Tiger has some useful built-in annotations Java.lang.Override Java.lang.Override Compiler enforces overriding superclass methods Compiler enforces overriding superclass methods Java.lang.Deprecated Java.lang.Deprecated Warns method, class or member is used Warns method, class or member is used Must use javac “-deprecation” argument to javac or the new - Xlint:deprecated flag to see compiler warnings Must use javac “-deprecation” argument to javac or the new - Xlint:deprecated flag to see compiler warnings Java.lang.SupressWarnings Java.lang.SupressWarnings Useful for Tiger’s many compiler warnings (especially with legacy collection code) Useful for Tiger’s many compiler warnings (especially with legacy collection code) Key: Look for a string enclosed in “[ ]” in compiler warnings from javac (may need to use the command line). Use this string to use for argument. Key: Look for a string enclosed in “[ ]” in compiler warnings from javac (may need to use the command line). Use this string to use for argument. This may work on your compiler yet! This may work on your compiler yet!

@Override Example Code: class Base { public void yes(int i) { } public void yes(int i) { }} class Subclass extends public void yes(int i) { } public void yes(int i) public void no(float x) { } // Compiler error generated here! public void no(float x) { } // Compiler error generated here!}

@Deprecated Example Example public class DeprecatedExample { private int x; private public int value; public public void setValue(int aValue) { value = aValue; } public void setValue(int aValue) { value = aValue; }} public class DeprecatedExampleUse { public static void main(String argv[]) public static void main(String argv[]) { DeprecatedExample obj = new DeprecatedExample(); // Compiler WARNINGs generated here DeprecatedExample obj = new DeprecatedExample(); // Compiler WARNINGs generated here obj.value = 10; // Compiler WARNING generated here obj.value = 10; // Compiler WARNING generated here }}

@SuppressWarning Example public class SuppressExample { List wordList = new ArrayList(); // no typing information on the List List wordList = new ArrayList(); // no typing information on the List private void private void generateWarning() generateWarning() { wordList.add("foo"); // Warning generated here. wordList.add("foo"); // Warning generated here. }} javac -Xlint:unchecked SuppressExample.java SuppressExample.java:13: warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List wordList.add("foo"); // Warning generated here. wordList.add("foo"); // Warning generated here. ^ 1 warning Get rid of warning by adding this line above the method

Setting Annotation Values Setting Annotation Values Setting Annotation Values Set arguments as key/value pairs Set arguments as key/value pairs Can optionally be an array of key value pairs Can optionally be an array of key value pairs “Marker” annotations “Marker” annotations No arguments No arguments Single value annotations Single value annotations no key is required, just a value no key is required, just a value Multiple value annotations Multiple value annotations separate key/value pairs with commas separate key/value pairs with commas Law”, grade=Grades.Pass) Law”, grade=Grades.Pass)

Java Annotations Metadata from annotations is available at compile-time and at runtime Metadata from annotations is available at compile-time and at runtime What for? What for? compile-time uses: Tools like a code generator or code validator (e.g. java.lang.Override) compile-time uses: Tools like a code generator or code validator (e.g. java.lang.Override) runtime uses: Any framework or application code that can make use of metadata (e.g. J2EE) runtime uses: Any framework or application code that can make use of metadata (e.g. J2EE)

Implementing and using custom annotations

A Sample Annotation Application A simple example to demo custom annotations A simple example to demo custom annotations The demo application is: We want to readily identify design patterns used in our production code The demo application is: We want to readily identify design patterns used in our production code Users put in annotation to identify design patterns in their code Users put in annotation to identify design patterns in their code annotation takes 3 arguments: annotation takes 3 arguments: PatternType = an enum for which design pattern (e.g. singleton, builder, etc.) PatternType = an enum for which design pattern (e.g. singleton, builder, etc.) Role = a string to denote the role played in more complex patterns (e.g. for an MVC pattern, role=“controller”) Role = a string to denote the role played in more complex patterns (e.g. for an MVC pattern, role=“controller”) Msg = a string to further explain pattern usage Msg = a string to further explain pattern usage

Sample usage #1 package samples.myapp; import custom.annotation.Pattern; import custom.annotation.PatternType; /** An example singleton that uses annotation. msg=“Singleton wrapper class”) public class SampleOne { private static SampleOne instance = null; private static SampleOne instance = null; private SampleOne() { } private SampleOne() { } public static SampleOne public static SampleOne get() get() { if (instance == null) if (instance == null) instance = new SampleOne(); instance = new SampleOne(); return(instance); return(instance); }}

Sample Usage #2 package samples.myapp; import custom.annotation.Pattern; import custom.annotation.PatternType; /** An example class that uses annotation. */ public class SampleTwo role="static factory role="static factory method") public static SampleTwo public static SampleTwo create(int aValue) create(int aValue) { SampleTwo instance = new SampleTwo(aValue); SampleTwo instance = new SampleTwo(aValue); return(instance); return(instance); } private int i; private int i; protected SampleTwo(int a) { i = a; } protected SampleTwo(int a) { i = a; } protected SampleTwo() { } protected SampleTwo() { }}

Implementing Annotations 4 standard meta-annotations you need to know about: 4 standard meta-annotations you need to know – specifies which Java elements can use the annotation (e.g. Type, method, constructor, – specifies which Java elements can use the annotation (e.g. Type, method, constructor, – specifies if annotation info is available at compile-time or at – specifies if annotation info is available at compile-time or at – Indicates if annotation should be part of public api. Annotation use shows up in – Indicates if annotation should be part of public api. Annotation use shows up in – Specify inheritance handling of the – Specify inheritance handling of the annotation

Implementing annotations 1. Declare meta-annotations for you custom annotation in the java etc. 2. Declare for your custom annotation in the java file Similar to a regular Java ‘interface’ Similar to a regular Java ‘interface’ Define “properties” of the annotation as methods Define “properties” of the annotation as methods

Annotation Implementation package custom.annotation; Import …. // Specify our meta-annoations ElementType.METHOD, // Tell javadoc to include usage of our custom annotations Pattern { // The design pattern enum value for the annotation instance. // The design pattern enum value for the annotation instance. PatternType type(); PatternType type(); // The "role" played in the design pattern. (value is optional) // The "role" played in the design pattern. (value is optional) String role() default "“; String role() default "“; // Some text to be displayed played in the design pattern. (optional) // Some text to be displayed played in the design pattern. (optional) String msg() default ""; String msg() default "";}

Annotation Implementation package custom.annotation; /** Declare the design patterns known by our annotation. */ public enum PatternType { /** A class which wraps a singleton object instance... blah. */ /** A class which wraps a singleton object instance... blah. */ SINGLETON_CLASS, SINGLETON_CLASS, /** A method used to constructs an object instance... blah. */ /** A method used to constructs an object instance... blah. */ FACTORY_METHOD, FACTORY_METHOD, /** A class which is used to... blah. */ /** A class which is used to... blah. */ BUILDER; BUILDER; public static String public static String getHtmlLink(PatternType pattern, String basePath) { … } getHtmlLink(PatternType pattern, String basePath) { … }}

Tools to use our custom type At runtime, you can get annotation values from java classes At runtime, you can get annotation values from java classes If you defined the annotation If you defined the annotation Use java reflection to pickup annotations from methods, members, etc. Use java reflection to pickup annotations from methods, members, etc. Demo a sample app which prints out all we used in our application code Demo a sample app which prints out all we used in our application code

Pattern Tool Source Code public class PatternTool { /** Processes annotations for a java class. The meat of our tool. */ /** Processes annotations for a java class. The meat of our tool. */ private void processPatternAnnotations(Class javaClass) throws IOException private void processPatternAnnotations(Class javaClass) throws IOException { // Get the declared upon class declaration // Get the declared upon class declaration if (javaClass.isAnnotationPresent(Pattern.class)) { if (javaClass.isAnnotationPresent(Pattern.class)) { Pattern classLevelPattern = (Pattern)javaClass.getAnnotation(Pattern.class); Pattern classLevelPattern = (Pattern)javaClass.getAnnotation(Pattern.class); printClassPattern(classLevelPattern, javaClass.getName()); printClassPattern(classLevelPattern, javaClass.getName()); } // Get all declared upon methods via reflection // Get all declared upon methods via reflection Method[] methods = javaClass.getDeclaredMethods(); Method[] methods = javaClass.getDeclaredMethods(); for (Method method : methods) { for (Method method : methods) { method.setAccessible(true); // make private methods accessible method.setAccessible(true); // make private methods accessible Pattern methodPattern = method.getAnnotation(Pattern.class); Pattern methodPattern = method.getAnnotation(Pattern.class); if (methodPattern != null) { if (methodPattern != null) { printMethodPattern(methodPattern, javaClass.getName(), method.getName()); printMethodPattern(methodPattern, javaClass.getName(), method.getName()); } } …code removed for clarity… …code removed for clarity…}

Sample HTML Output Design Pattern Usage Java Class: samples.myapp.SampleOne samples.myapp.SampleOne Class level design pattern implemented: Singleton Class Design Pattern, Msg: ‘Singleton Wrapper Class’ Singleton Class Design PatternSingleton Class Design Pattern Java Class: samples.myapp.SampleTwo samples.myapp.SampleTwo Method create() implements design pattern: Factory Method Pattern, Role: 'static factory method' create()Factory Method Patterncreate()Factory Method Pattern

Some Ideas on how to apply annotations Things to make you think about how annotations can be used

Replace older technology Replace javadoc-oriented precompilers Replace javadoc-oriented precompilers Provide runtime access to metadata - not just compile-time. Provide runtime access to metadata - not just compile-time. Metadata syntax checked by java compiler Metadata syntax checked by java compiler Replace XML-oriented java tools Replace XML-oriented java tools Put metadata in your java files were it is easy to maintain - not in separate XML files Put metadata in your java files were it is easy to maintain - not in separate XML files Do away with verbose, error-prone XML typing Do away with verbose, error-prone XML typing Typically easier to find and fix errors than fiddling with the XML parsing + Java errors Typically easier to find and fix errors than fiddling with the XML parsing + Java errors Provide built-in type checking for metadata via java compiler Provide built-in type checking for metadata via java compiler Rapidly replacing XML usage in J2EE in many areas Rapidly replacing XML usage in J2EE in many areas

Application Idea: Binding a pojo to user interface resetbutton=false) Public class PersonInfo type=FormField.TEXT, size=25, printf=“%s”) public Sting type=FormField.RADIO, type=FormField.RADIO, isReqd=true) public State type=FormField.TEXT, printf=“%d”) public Integer age; …}

Application ideas: User Input public class PersonPojo max=115) public int public Integer numberOfDependents; …}

Application: com.acme.Metrics.class, com.acme.CustomSecurity.class}) public class AccountManagementBean implements AccountManagement { public void createAccount(int accountNumber, AccountDetails details) {... }...} public class Metrics public Object profile(InvocationContext inv) throws Exception { long time = System.currentTimeMillis(); try { return inv.proceed(); } finally { long endTime = time - System.currentTimeMillis(); System.out.println(inv.getMethod() + " took " + endTime + “ milliseconds."); }}} public class AccountAudit public Object auditAccountOperation(InvocationContext inv) throws Exception { try { Object result = inv.proceed(); Auditor.audit(inv.getMethod().getName(), inv.getParameters[0]); return result; } catch (Exception ex) { Auditor.auditFailure(ex); throw ex; } }} public class CustomSecurity public Object customSecurity(InvocationContext inv) throws Exception….

Application: EJB public class Maintainence { public void importCompanyData () {...} public void restart () public class HRActivity public void addToPayroll () “Manager”}) public void postJobOpening() {...}...}

Application Idea: Code Maintentance Annotations Public class MyAppClass { // Tags to generate documentation of SQL used in your application so it’s easier to // figure out implications of dbms schema changes and dbms protected static final String sql = “select id, version from astro_entity where type = ?”; public ArrayList getSuperNova(String snType) { ….} // Tags to generate documentation on hacks and things todo for future linear sort algorithm”, fix=“Use tree sorting to separate class”) public void sortSuperNova(ArrayList sn) {…}