Saturday, 28 February 2015

Annoatations --2

The compiler generates a warning when we use deprecated elements.
                                       
Example on @Deprecated
1.       public class DeprecatedDemo{
2.           /**
3.             * @deprecated this method got deprecated it better
4.             *  to use {@link BetterSum#sum(int, int)}
5.             */
6.             @Deprecated
7.              public void sum ( int a, int b)  {
8.                     System.out.println(a+b);
9.                }
10.    
11.          public static void main(String[] args)
12.           {
13.                 DeprecatedDemo demo= new DeprecatedDemo();
14.                  demo.sum();
15.            }
16.   }

NOTE: when we call sum() method, it will show warning, so that the method got deprecated

Source code of @Deprecated
1.             @Documented
2.             @RetentionPolicy.RUNTIME)
3.             public @interface Deprecated{
4.        
5.             }

@SuppressWarnings
ð  SuppressWarnings annotation indicates to the compiler to suppress all the compiler warnings in the annotated code element including its sub elements or block.

ð  We should use @SuppressWarnings when we know that we are using on API which results warnings, have taken possible precautions and therefore we don’t want the compiler to warn about the same.

Example on @SuppressWarnings
1.       package com.nit.annotation;
2.       import java.util.ArrayList;
3.       import java.util.List;
4.       //@SuppressWarnings("deprecation ")
5.       public class SuppressWarningDemo {
6.               @SuppressWarnings("all")
7.               public static void main(String[] args) {
8.                      List list=new ArrayList();
9.                      list.add("hi");
10.                  list.add("hello");
11.                  System.out.println(list);
12.        }
13.        public void test(){
14.             Int a;
15.        }
16.    
17.   }

Source code of @SuppressWarnings
1.       @Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
2.       @Retention(RetentionPolicy.SOURCE)
3.       public @interface SuppressWarnings{
4.             String[] value();
5.       }

The following are different values for SuppressWarning annotation
all, boxing, cast, dep-ann, deprecation, fallthrough, finally, hiding, incomplete-switch, nls, null, rawtypes, restriction, serial, static-access, synthetic-access, unchecked, unqualified-fieldaccess
Annotation type
TYPE
FIELD
METHOD
PARAMETER
CONSTRUCTOR
LOCAL-VARIABLE
PACKAGES
ANNOTATION-TYPE
@SuppressWarnings
Applicable
Applicable
Applicable
Applicable
Applicable
Applicable
Notapplicable
Notapplicable
@Override
Notapplicable
Notapplicable
applicable
Notapplicable
Notapplicable
Notapplicable
Notapplicable
Notapplicable
@Deprecated
Applicable
Applicable
Applicable
Applicable
Applicable
Applicable
Applicable
applicable

Enum types
ð An enum type is a type whose fields consist of a fixed set of constants.
ð Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST),  days of the week,  planet names…etc.
Simple enum. The ; after the last element is optional, when this is the end of enum definition.
public enum Color {
 WHITE, BLACK, RED, YELLOW, BLUE;  //; is optional
}
Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.

public class Outter {

 public enum Color {

   WHITE, BLACK, RED, YELLOW, BLUE

 }

}
Enum that overrides toString method. A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here.

public enum Color {

 WHITE, BLACK, RED, YELLOW, BLUE;  //; is required here.



 @Override public String toString() {

   //only capitalize the first letter

   String s = super.toString();

   return s.substring(0, 1) + s.substring(1).toLowerCase();

 }

}
Enum with additional fields and custom constructor. Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.
public enum Color {

 WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);



 private int code;



 private Color(int c) {

   code = c;

 }



 public int getCode() {

   return code;

 }
Enum that implements interfaces. Enum can implement any interfaces. All enum types implicitly implements java.io.Serializable, andjava.lang.Comparable.
public enum Color implements Runnable {

 WHITE, BLACK, RED, YELLOW, BLUE;



 public void run() {

   System.out.println("name()=" + name() +

       ", toString()=" + toString());

 }

}
A sample test program to invoke this run() method:

for(Color c : Color.values()) {

 c.run();

}
Or,

for(Runnable r : Color.values()) {
 r.run();
}
Example on Enum Types
Direction.java
1.       package com.neo.enums;
2.        
3.       public enum Direction {
4.               NORTH(1), EAST(2), SOUTH(3), WEST(4);
5.        
6.               private int code;
7.        
8.               private Direction(int code) {
9.                               this.code = code;
10.           }
11.          
12.           public int getCode(){
13.                           return code;
14.           }
15.    
16.   }

EnumDemo.java
1.       package com.neo.enums;
2.        
3.       public class EnumDemo {
4.               public static void main(String[] args) {
5.                               sop("Accessing perticular instance...");
6.                               Direction direction = Direction.SOUTH;
7.                               System.out.println(direction);
8.                               sop("...all instances of Direction are...");
9.                               for (Direction direction2 : Direction.values()) {
10.                                           sop(direction2 + "==>" + direction2.getCode());
11.                           }
12.                          
13.           }
14.    
15.           public static void sop(Object object) {
16.                           System.out.println(object);
17.           }
18.   }


Types of Annotations
       There are 4 types of annotations
1.   marker annotation
2.   single member annotation
3.   multimember (or)full annotation
4.   complex (or) nested annotation

Marker Annotation
ð  This annotation is just like marker interface. So marker annotations can be used as an alternative to marker interfaces.

ð  Marker Annotation is a special kind of annotation that contains no members. Its main purpose is to mark java elements. The presence of marker annotation carries a special meaning to a java element.

Ex : Override, Deprecated, Documented, Inherited
Creation of marker annotation
Immutable.java
19.   @Target(ElementType.TYPE)          
20.   public @interface Immutable{
21.    
22.   }

Usage of marker annotation
Account.java
1.       @Immutable
2.       public class Account{
3.        
4.       }

Single member annotation
ð  A single member annotation contains only one member

ð  It works like a normal annotation except that it allows a short hand form of specifying the value of the member. when only one member is present (with name “value”) you can simply specify the value for that member when the annotation is applied. We don’t need to specify the name of the member.

ð  However in order to use this short hand the name of the member must be value.

Ex: SupressWarnings, Retention, Target …etc.
Example
Usage
Public @interface Author{
              String value();
}

@Author(“sekhar”)
 public class Demo{
}
@Author(value=“sekhar”)
public class Demo{
}

Example
Usage
Public @interface Author{
              String name();
}

@Author(name=“sekhar”)
public class Demo{
}

ð  Annotations can have array members also.
ð  Array members can be primitive type, String, enum type or other annotation type or class only.

Example
Usage
Public @interface Author{
              String[] value();
}

@Author({“kesav”,”sekhar”,”somu”})
 public class Demo{
}
@Author(value={“kesav”,”sekhar”,”somu”})
public class Demo{
}

ð  When the annotation has a member while using this annotation we should specify the member value otherwise compilation error will be generated.

ð  Annotation members can have default values. Those default values will be used if we don’t specify the value for a member when the annotation is applied. Default value is specified by adding default clause to a member’s declaration.

Example
Usage
Public @interface Author{
              String value() default “sekhar”;
}

@Author(”somu”) // overridden the default
 public class Demo{
}
@Author // default value will be taken
public class Demo{
}

Multimember Annotation
ð  An annotation which will contain more than one member is called multimember annotation or full annotation. While applying multimember annotation shorthand form is not allowed.

ð  While applying the multi member annotation, members should be specified as key-value pairs separated by ‘,’(comma).

Example
Usage
public @interface Author{
              String name();
              String version() default “1.6”;
}

@Author(name=”sekhar”,  version=”1.8”)
 public class Demo{
}
Subject.java
public enum Subject {
                STRUTS, SPRING, HIBERNATE;
}

Author.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
public @interface Author {
                String[] name() default "sekhar";
                double version() default 1.0;
                boolean maritalStatus() ;
                Subject subName();
}

Demo.java
@Author(subName=Subject.SPRING,maritalStatus=false, version=1.0)
public class Demo {

}

Complex (or) Nested Annotation
ð  Defining an annotation inside another annotation is called nested annotation.

Licence.java
1.       public @interface Licence{
2.             String place() default “Tenali”;
3.       }

TrafficOfficer.java
1.       public @interface TrafficOfficer {
2.               Licence licence();
3.               String showMeLicence();
4.       }

Demo.java
1.       @TrafficOfficer(licence=@Licence(place="Hyd"),showMeLicence="sorry sir take 200Rs")
2.       public class Demo {
3.       }

APT(Annotation Processor Tool)



No comments:

Post a Comment