Java Annotations Annotations o Annotations are metadata or

  • Slides: 27
Download presentation
Java Annotations

Java Annotations

Annotations o Annotations are metadata or data about data. An annotation indicates that the

Annotations o Annotations are metadata or data about data. An annotation indicates that the declared element should be processed in some special way by a compiler, development tool, deployment tool, or during runtime. o Annotation-based development is certainly one of the latest Java development trends o Annotations can be applied to several Java Elements like, n package declarations, n class, n constructors, n methods, n fields, n Variables and etc.

The Basics o Example to Define an Annotation (Annotation type) public @interface My. Annotation

The Basics o Example to Define an Annotation (Annotation type) public @interface My. Annotation { String do. Something(); } o Example to Annotate Your Code (Annotation) My. Annotation (do. Something="What to do") public void mymethod() {. . . . }

Structure of Java Compiler Source File Type Checker Parser Class File class C {

Structure of Java Compiler Source File Type Checker Parser Class File class C { @Non. Null Object field; C(@Non. Null Object p) { field = p; } @Non. Null Object get() { return field; } Class File Writer Comments } Error

Structure of Java 5 Compiler Source File Type Annotation Class File Checker Writer Parser

Structure of Java 5 Compiler Source File Type Annotation Class File Checker Writer Parser Class File class C { @Non. Null Object field; C(@Non. Null Object p) { field = p; } @Non. Null Object get() { return field; } } Program with annotations Error Annotation Checker Plugins

Annotation Types o Marker o Single-Element o Full-value or multi-value

Annotation Types o Marker o Single-Element o Full-value or multi-value

Marker annotations take no parameters. They are used to mark a Java element to

Marker annotations take no parameters. They are used to mark a Java element to be processed in a particular way. o o Example: public @interface My. Annotation { } Usage: @My. Annotation public void mymethod() {. . }

Single-Element o Single-element, or single-value type, annotations provide a single piece of data only.

Single-Element o Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis. o Example: o Usage: public @interface My. Annotation { String do. Something(); } @My. Annotation ("What to do") public void mymethod() {. . }

Full-value or multi-value o Full-value type annotations have multiple data members. o Example: o

Full-value or multi-value o Full-value type annotations have multiple data members. o Example: o Usage: @My. Annotation (do. Something= "What to do", count=1, date="09 -09 -2005") public void mymethod() {. . } public @interface My. Annotation { String do. Something(); int count; String date(); }

The Built-In Annotations o Java defines seven built-in annotations. o Four are imported from

The Built-In Annotations o Java defines seven built-in annotations. o Four are imported from java. lang. annotation o o @Retention, @Documented, @Target, and @Inherited. o Three are included in java. lang. n @Override, n @Deprecated, n and @Suppress. Warnings.

Simple Annotations (or) Standard Annotations o There are three types of simple annotations provided

Simple Annotations (or) Standard Annotations o There are three types of simple annotations provided by JDK 5. They are: n Override n Deprecated n Suppresswarnings

Override o Override is a Marker Annotation type that can be applied to a

Override o Override is a Marker Annotation type that can be applied to a method to indicate to the Compiler that the method overrides a method in a Superclass. This Annotation type guards the programmer against making a mistake when overriding a method. For eg The syntax ---@Override o Example Program: class Parent { public float calculate (float a, float b) { return a * b; } } Whenever you want to override a method, declare the Override annotation t ype before the method: public class Child extends Parent { @Override public int calculate (int a, int b) { return (a + 1) * b; } }

The Deprecated annotation o o o This annotation indicates that when a deprecated program

The Deprecated annotation o o o This annotation indicates that when a deprecated program element is used, the compiler should warn you about it. Example 2 shows you the deprecated annotation. The syntax --- @Deprecated Example : public class Deprecated. Test { @Deprecated public void serve() { } } If you use or override a deprecated method, you will get a warning at compile time. public class Deprecated. Test 2 { public static void main(String[] args) { Deprecated. Test test = new Deprecated. Test(); test. serve(); } }

The Suppresswarnings annotation o Suppress. Warnings is used to suppress compiler warnings. You can

The Suppresswarnings annotation o Suppress. Warnings is used to suppress compiler warnings. You can apply @Suppress. Warnings to types, constructors, methods, fields, parameters, and local variables. o The syntax --- @Suppress. Warnings o Eg: import java. util. Date; public class Main { @Suppress. Warnings(value={"deprecation"}) public static void main(String[] args) { Date date = new Date(2009, 9, 30); } } System. out. println("date = " + date);

Documentation o public class Generation 3 List extends { // // Author: John Doe

Documentation o public class Generation 3 List extends { // // Author: John Doe Date: 3/17/2002 Current revision: 6 Last modified: 4/12/2004 By: Jane Doe Reviewers: Alice, Bill, Cindy class code goes here } o Using Java Annotation n } n ) @Documented @interface Class. Preamble { String author(); String date(); int current. Revision() default 1; String last. Modified() default "N/A"; String last. Modified. By() default "N/A"; String[] reviewers(); @Class. Preamble ( author = "John Doe", date = "3/17/2002", current. Revision = 6, last. Modified = "4/12/2004", last. Modified. By = "Jane Doe", reviewers = {"Alice", "Bob", "Cindy"}

The Target annotation o @Target(Element. Type. TYPE)—can be applied to any element of a

The Target annotation o @Target(Element. Type. TYPE)—can be applied to any element of a class o @Target(Element. Type. FIELD)—can be applied to a field or property o @Target(Element. Type. METHOD)—can be applied to a method level annotation o @Target(Element. Type. PARAMETER)—can be applied to the parameters of a method o @Target(Element. Type. CONSTRUCTOR)—can be applied to constructors o @Target(Element. Type. LOCAL_VARIABLE)—can be applied to local variables o @Target(Element. Type. ANNOTATION_TYPE)—indicates that the declared type itself is an

Java Annotation in Struts 2 o Two mechanisms for declaring your architecture n XML

Java Annotation in Struts 2 o Two mechanisms for declaring your architecture n XML n Java annotations

Design

Design

Struts 2 Feature o "zero configuration" n Convention over configuration: this means that if

Struts 2 Feature o "zero configuration" n Convention over configuration: this means that if you follow some standard naming conventions and place your Struts 2 actions in the "correct" location, then Struts will take care of finding them and configuring your application for you — meaning that you will have far less manual configuration. n Java Annotations

web. xml o <? xml version="1. 0" encoding="UTF-8"? > <web-app xmlns: xsi="http: //www. w

web. xml o <? xml version="1. 0" encoding="UTF-8"? > <web-app xmlns: xsi="http: //www. w 3. org/2001/XMLSchema-instance" xmlns="http: //java. sun. com/xml/ns/javaee" xmlns: web="http: //java. sun. com/xml/ns/javaee/web-app_2_5. xsd" xsi: schema. Location="http: //java. sun. com/xml/ns/javaee/web-app_2_5. xsd" id="Web. App_ID" version="2. 5"> <display-name>Hello. Struts 2 <!-- Define our Struts 2 Servlet Filter --> <filter-name>struts 2</filter-name> <filter-class>org. apache. struts 2. dispatcher. Filter. Dispatcher</filter-class> <init-param> <param-name>action. Packages</param-name> <param-value>com. geekcap. struts 2</param-value> </init-param> </filter> <!-- Map all requests to the Struts 2 servlet --> <filter-mapping> <filter-name>struts 2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index. html</welcome-file> </welcome-file-list> </web-app>

How it works o For Eg: n We are going to have a package

How it works o For Eg: n We are going to have a package name as com. greekcap. struts 2 n And the Sub-Package name as action o Place the class files inside the Action Package o http: //localhost: 8080/Hello. Struts 2/action/<actionname>. action o The next step is to define the action name. Action classes can be defined in two ways: n Configuration: implement the Action interface n Convention: name your class so that it ends with the word Action

How Filter. Dispatcher will Identify the Class o the Action interface, or o extends

How Filter. Dispatcher will Identify the Class o the Action interface, or o extends the Action. Support class, and provide an execute() method that returns a String, then the Filter. Dispatcher will identify your class o On the other hand, you are not required to implement the Action interface if your class name ends in Action and it provides an execute() method that returns a String.

When the Filter. Dispatcher finds such a class, it defines the action name as

When the Filter. Dispatcher finds such a class, it defines the action name as follows: o Remove the word "Action" from the end of the class name o Convert the first character in the class name to lower case n http: //localhost: 8080/Hello. Struts 2/actio n/<action-name>. action n http: //localhost: 8080/Hello. Struts 2/actio n/hello. action

Hello. Action. java o package com. geekcap. struts 2. action; import org. apache. struts

Hello. Action. java o package com. geekcap. struts 2. action; import org. apache. struts 2. config. Result; @Result(name="success", value="/hello. jsp") public class Hello. Action { private String name; public String execute() { return "success"; } } public String get. Name() { return name; } public void set. Name(String name) { this. name = name; }

1. hello. Form. jsp <html><body> <s: form action="hello"> <s: textfield name="name“ label="Your name"/> <s:

1. hello. Form. jsp <html><body> <s: form action="hello"> <s: textfield name="name“ label="Your name"/> <s: submit/> </s: form> </body></html> 2. hello. jsp <html> <body> <h 4>Hello, <s: property value="name"/> !</h 4> </body> </html>

Struts 2 Validation Using Java Annotation o package net. roseindia; import com. opensymphony. xwork

Struts 2 Validation Using Java Annotation o package net. roseindia; import com. opensymphony. xwork 2. Action. Support; mport com. opensymphony. xwork 2. validator. annotations. *; @Validation public class Annotation. Action extends Action. Support { private String username = null; private String password = null; o o @Required. String. Validator(message="Supply name") public String get. Username() { return username; } public void set. Username(String value) { username = value; } @Required. String. Validator(message="Supply password") public String get. Password() { return password; } o o public void set. Password(String value) { password = value; } public String execute() throws Exception { System. out. println("Validating login"); if(!get. Username(). equals("Admin") || !get. Password(). equals("Admin")){ add. Action. Error("Invalid user name or password! Please try again!"); return ERROR; } else{ return SUCCESS; } }}

Thank You

Thank You