270 likes | 779 Views
Java Annotations. Annotations . 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.
E N D
Annotations • 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. • Annotation-based development is certainly one of the latest Java development trends • Annotations can be applied to several Java Elements like, • package declarations, • class, • constructors, • methods, • fields, • Variables and etc.
The Basics • Example to Define an Annotation (Annotation type) public @interface MyAnnotation { String doSomething(); } • Example to Annotate Your Code (Annotation) MyAnnotation (doSomething="What to do") public void mymethod() { ....... }
Parser Type Checker Class File Writer Error Structure of Java Compiler Source File Class File class C { @NonNull Object field; C(@NonNull Object p) { field = p; } @NonNull Object get() { return field; } } Comments
Parser Annotation Checker Type Checker Class File Writer Structure of Java5 Compiler Source File Class File class C { @NonNull Object field; C(@NonNull Object p) { field = p; } @NonNull Object get() { return field; } } Program with annotations Error Error Annotation Checker Plugins
Annotation Types • Marker • Single-Element • Full-value or multi-value
Marker Marker annotations take no parameters. They are used to mark a Java element to be processed in a particular way. • Example: public @interface MyAnnotation { } • Usage: @MyAnnotation public void mymethod() { .... }
Single-Element • 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. • Example: public @interface MyAnnotation { String doSomething(); } • Usage: @MyAnnotation ("What to do") public void mymethod() { .... }
Full-value or multi-value • Full-value type annotations have multiple data members. • Example: public @interface MyAnnotation { String doSomething(); int count; String date(); } • Usage: @MyAnnotation (doSomething= "What to do", count=1, date="09-09-2005") public void mymethod() { .... }
The Built-In Annotations • Java defines seven built-in annotations. • Four are imported from java.lang.annotation • @Retention, • @Documented, • @Target, • and @Inherited. • Three are included in java.lang. • @Override, • @Deprecated, • and @SuppressWarnings.
Simple Annotations (or) Standard Annotations • There are three types of simple annotations provided by JDK5. They are: • Override • Deprecated • Suppresswarnings
Override • 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 • 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 type before the method:public class Child extends Parent { @Overridepublic int calculate (int a, int b) {return (a + 1) * b; }}
The Deprecated annotation • 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 DeprecatedTest { @Deprecatedpublic void serve() { }} If you use or override a deprecated method, you will get a warning at compile time. public class DeprecatedTest2 {public static void main(String[] args) { DeprecatedTest test = new DeprecatedTest(); test.serve(); } }
The Suppresswarnings annotation • SuppressWarnings is used to suppress compiler warnings. You can apply @SuppressWarnings to types, constructors, methods, fields, parameters, and local variables. • The syntax --- @SuppressWarnings • Eg: import java.util.Date;public class Main { @SuppressWarnings(value={"deprecation"})public static void main(String[] args) { Date date = new Date(2009, 9, 30); System.out.println("date = " + date); }}
Documentation • public class Generation3List 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 } • Using Java Annotation • @Documented @interface ClassPreamble { String author(); String date(); int currentRevision() default 1; String lastModified() default "N/A"; String lastModifiedBy() default "N/A"; String[] reviewers(); } • @ClassPreamble ( author = "John Doe", date = "3/17/2002", currentRevision = 6, lastModified = "4/12/2004", lastModifiedBy = "Jane Doe", reviewers = {"Alice", "Bob", "Cindy"} )
The Target annotation • @Target(ElementType.TYPE)—can be applied to any element of a class • @Target(ElementType.FIELD)—can be applied to a field or property • @Target(ElementType.METHOD)—can be applied to a method level annotation • @Target(ElementType.PARAMETER)—can be applied to the parameters of a method • @Target(ElementType.CONSTRUCTOR)—can be applied to constructors • @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables • @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an
Java Annotation in Struts2 • Two mechanisms for declaring your architecture • XML • Java annotations
Struts 2 Feature • "zero configuration" • 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. • Java Annotations
web.xml • <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.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:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>HelloStruts2 <!-- Define our Struts2 Servlet Filter --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> <init-param> <param-name>actionPackages</param-name> <param-value>com.geekcap.struts2</param-value> </init-param> </filter> <!-- Map all requests to the Struts 2 servlet --> <filter-mapping> <filter-name>struts2</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 • For Eg: • We are going to have a package name as com.greekcap.struts2 • And the Sub-Package name as action • Place the class files inside the Action Package • http://localhost:8080/HelloStruts2/action/<action-name>.action • The next step is to define the action name. Action classes can be defined in two ways: • Configuration: implement the Action interface • Convention: name your class so that it ends with the word Action
How FilterDispatcher will Identify the Class • the Action interface, or • extends the ActionSupport class, and provide an execute() method that returns a String, then the FilterDispatcher will identify your class • 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 FilterDispatcher finds such a class, it defines the action name as follows: • Remove the word "Action" from the end of the class name • Convert the first character in the class name to lower case • http://localhost:8080/HelloStruts2/action/<action-name>.action • http://localhost:8080/HelloStruts2/action/hello.action
HelloAction.java • package com.geekcap.struts2.action; import org.apache.struts2.config.Result; @Result(name="success", value="/hello.jsp") public class HelloAction { private String name; public String execute() { return "success"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
1.helloForm.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> <h4>Hello, <s:property value="name"/> !</h4> </body> </html>
Struts2 Validation Using Java Annotation • package net.roseindia;import com.opensymphony.xwork2.ActionSupport; mport com.opensymphony.xwork2.validator.annotations.*;@Validation public class AnnotationAction extends ActionSupport {private String username = null; private String password = null; • @RequiredStringValidator(message="Supply name") public String getUsername() {return username; } • public void setUsername(String value) { username = value; }@RequiredStringValidator(message="Supply password") public String getPassword() { return password; } • public void setPassword(String value) { password = value; } • public String execute() throws Exception {System.out.println("Validating login");if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){ addActionError("Invalid user name or password! Please try again!"); return ERROR; }else{ return SUCCESS;} }}