Translate

Wednesday, October 31, 2012

Java Annotations


                                                                         Annotations


Overview of Annotations

Annotations are notes for the Java compiler. When you annotate a program element in a source file, you add notes to the Java program elements in that source file. You can annotate Java packages, types (classes, interfaces, enumerated types), constructors, methods, fields, parameters, and local variables. For example, you can annotate a Java class so that any warnings that the javac program would otherwise issue will be suppressed. Or, you can annotate a method that you want to override to ask the compiler to verify that you are really overriding the method, not overloading it. The Java compiler can be instructed to interpret annotations and discard them (so those annotations only live in source files) or include them in resulting Java classes. Those that are included in Java classes may be ignored by the Java virtual machine, or they may be loaded into the virtual machine. The latter type is called runtime-visible and you can use reflection
to inquire about them.

Annotations and Annotation Types

When studying annotations, you will come across these two terms very frequently: annotations and annotation types. To understand their meanings, it is useful to first bear in mind that an annotation type is a special interface type. An annotation is an instance of an annotation type. Just like an interface, an annotation type has a name and members. The information contained in an annotation takes the form of key/value pairs. There can be zero or multiple pairs and each key has a specific type. It can be a String, int, or other Java types. Annotation types with no key/value pairs are called marker annotation types. Those with one key/value pair are often referred to single-value annotation types. Annotations were first added to Java 5, which brought with it, three annotation types: Deprecated Override, and Suppress Warnings. They for example, here is how you use the marker annotation type Deprecated:

@Deprecated
And, this is how you use the second syntax for multi-value annotation type
Author:
@Author(firstName="Ted",lastName="Diong")
There is an exception to this rule. If an annotation type has a single  key/value pair and the name of the key is value, then you can omit the key from the bracket. Therefore, if fictitious annotation type Stage has a single key named value, you can write
@Stage(value=1) or @Stage(1)
Returns a string representation of this annotation, which typically lists all the key/value pairs of this annotation.

Standard Annotations:

Annotations were a new feature in Java 5 and originally there were three standard annotations, all of which are in the java.lang package: Override, Deprecated, and Suppress Warnings.

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. and Child classes. However, you won’t be always this lucky. Sometimes the parent class is buried somewhere in another package. This seemingly trivial error could be fatal because when a client class calls the calculate method on a Child object and passes two floats, the method in the Parent class will be invoked and the wrong result returned. Using the Override annotation type will prevent this kind of mistake. Whenever you want to override a method, declare the Override annotation type before the method:

Ex:-

public class Child extends Parent
 {
    @Override
    public int calculate(int a, int b)
   {
        return (a + 1) * b;
    }
}
This time, the compiler will generate a compile error and you’ll be notified that the calculate method in Child is not overriding the method in the parent class. It is clear that @Override is useful to make sure programmers override a method when they intend to override it, and not overload it.

Deprecated
Deprecated is a marker annotation type that can be applied to a method or a type to indicate that the method or type is deprecated. A deprecated method or type is marked so by the programmer to warn the users of his code that they should not use or override the method or use or extend the type. The reason why a method or a type is marked deprecated is usually because there is a better method or type and the deprecated method or type is retained in the current software version for backward compatibility. For example, the DeprecatedTest class in Ex.1 uses the Deprecated annotation type.

Ex.1: Deprecating a method
package app1;
public class DeprecatedTest
{
   @Deprecated
    public void serve()
   {    }
}
If you use or override a deprecated method, you will get a warning at compile time. For example, EX.2 shows a DeprecatedTest2 class that uses the serve method in DeprecatedTest.

Ex.2: Using a deprecated method
package app1;
public class DeprecatedTest2
{
    public static void main(String[] args)
   {
        DeprecatedTest test = new DeprecatedTest();
        test.serve();
    }
}
Compiling DeprecatedTest2 generates this warning: Note: app1/DeprecatedTest2.java uses or overrides a deprecated

Suppress Warnings:

Suppress Warnings is used, as you must have guessed, to suppress compiler warnings. You can apply @SuppressWarnings to types, constructors, methods, fields, parameters, and local variables. You use it by passing a String array that contains warnings that need to be suppressed. Its syntax is as follows.

                          @SuppressWarnings(value={string-1, ..., string-n})

Where string-1 to string-n indicate the set of warnings to be suppressed. Duplicate and unrecognized warnings will be ignored.The following are valid parameters to @SuppressWarnings:

▪unchecked. Gives more detail for unchecked conversion warnings that are mandated by the Java Language Specification.

▪path. Warns about nonexistent path (classpath, sourcepath, etc) directories.

As an example, the SuppressWarningsTest class in Ex:-.4 uses the SuppressWarnings annotation type to prevent the compiler from issuing unchecked and fallthrough warnings.


Ex 4 Using @SuppressWarnings

package app1;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
@SuppressWarnings(value={"unchecked","serial"})
public class SuppressWarningsTest implements Serializable
{
    public void openFile()
    {
        ArrayList a = new ArrayList();
        File file = new File("X:/java/doc.txt");
    } 
}

Common Annotations:

  ▪ comments. Comments accompanying the generated code. For example, in Ex.5 @Generated is used to annotate a generated class.

Ex.5: Using @Generated
package app18;
import javax.annotation.Generated;
@Generated(value="com.chandrasoftware.robot.CodeGenerator",
        date="2012-11-31", comments="Generated code")
public class GeneratedTest
{
}

Standard Meta-Annotations:
Meta annotations are annotations that annotate annotations. There are four meta-annotation types that can be used to annotate annotations: Documented, Inherited, Retention, and Target. All the four are part of the java.lang.annotation package. This section discusses these annotations
                        types.
                        Documented
Documented is a marker annotation type used to annotate the declaration of an annotation type so that instances of the annotation type will be included in the documentation generated using Javadoc or similar tools.For example, the Override annotation type is not annotated using Documented. As a result, if you use Javadoc to generate a class whose
method is annotated @Override, you will not see any trace of @Override in the resulting document. For instance, Ex.6 shows a OverrideTest2 class that uses @Override to annotate the toString method.

Ex.6: The OverrideTest2 class
package app1;
public class OverrideTest2
{
    @Override
    public String toString()
    {
        return "OverrideTest2";
    }
}

On the other hand, the Deprecated annotation type is annotated @Documented. Recall that the serve method in the DeprecatedTest class in Ex.2 is annotated @Deprecated. Now, if you use Javadoc to generate the documentation for OverrideTest2 the details of the serve method in the documentation will also include @Deprecated, like this: serve
@Deprecated
public void serve()
▪SOURCE. Annotations are to be discarded by the Java compiler.
▪CLASS. Annotations are to be recorded in the class file but not retained by the JVM.           This is the default value.
▪RUNTIME. Annotations are to be retained by the JVM so they can be queried using reflection. For example, the declaration of the SuppressWarnings annotation type is annotated @Retention with the value of SOURCE.

@Retention(value=SOURCE)
public @interface SuppressWarnings

Target:
Target indicates which program element(s) can be annotated using instances of the annotated annotation type. The value of Target is one of the members of the java.lang.annotation.ElementType enum: As an example, the Override annotation type declaration is annotated the following Target annotation, making Override only applicable to method declarations.

@Target(value=METHOD)

You can have multiple values in the Target annotation. For example, this is from the declaration of SuppressWarnings:
@Target(value={TYPE,FIELD, METHOD, PARAMETER,CONSTRUCTOR,
LOCAL_VARIABLE})

Custom Annotation Types:

An annotation type is a Java interface, except that you must add an at sign before the interface keyword when declaring it.

public @interface CustomAnnotation
{
}
Using Custom Annotation Types:

The Author annotation type is like any other Java type. Once you import it into a class or an interface, you can use it simply by writing

@Author(firstName="firstName",lastName="lastName", internalEmployee=true|false)
For example, the Test1 class in Ex.8 is annotated Author.

 Ex.8: A class annotated Author
package app1.custom;
@Author(firstName="John",lastName="Guddell",internalEmployee=true)
public class Test1 {
}
The next subsection “Using Reflection to Query Annotations” shows how the Author annotations can be of good use. Using Reflection to Query Annotations The java.lang.Class class has several methods related to annotations.

present.
Otherwise, returns null. public java.lang.annotation.Annotation[] getAnnotations()
Returns all annotations present on this class.

public boolean isAnnotation() Returns true if this class is an annotation type.
public boolean isAnnotationPresent(Class
        java.lang.annotation.Annotation> annotationClass)

Indicates whether an annotation for the specified type is present on this class The app1.custom package includes three test classes, Test1, Test2, and Test3, that are annotated Author. Ex.9 shows a test class that employs reflection to query the test classes.
Ex.9: Using reflection to query annotations
package app1.custom;
public class CustomAnnotationTest
{
    public static void printClassInfo(Class c)
    {
        System.out.print(c.getName() + ". ");
        Author author = (Author) c.getAnnotation(Author.class);
        if (author != null)
       {
            System.out.println("Author:" + author.firstName()
                    + " " + author.lastName());
        } else {
            System.out.println("Author unknown");
        }   
    }
    public static void main(String[] args)
    {
        CustomAnnotationTest.printClassInfo(Test1.class);
    }
}

Tuesday, October 30, 2012

Design Patterns(Creational Design Patterns)


Design Patterns



                       Design patterns are the set of rules as best solutions for re-occurring problems of application development. Senior Software Engineer’s prepares Design Patterns based on experience. Junior Software Engineers will use them in project implementation most of the Design Patterns are give by a team called GOf.

                        The worst solutions for re-occurring problems are for application development is called anti patterns every software technologies contain Design Patterns to utilize those software technologies more effetely.

Design Patterns are the best practices of application development by using software technologies more effetely.

Basic Design Patterns or Creational Design Patterns.:

  1. Factory Method
  2. Singleton Java class
  3. Factory
  4. Abstract Factory
  5. Builder
  6. Proto Type
  7. IOC(Inversion of Control)/DI(Dependence Injection)
  8. Template Method
  9. Value Object (Or) Data Transfer Object
  10. Adapter Class
  
  1. Factory Method:

A method in a java class that is capable of constructing its own java class object is called Factory Method.

Problem: - We can’t create object of a java class out side the class. When class contain only private constructer.

Solution: - Add Factory Method in that class rules implemented to factory method.
          
    1. Recommended to take method as public static method
    2. Return type of method must be a class name..

    

  Class Test                                         Test t = new Test ();    -------à  X
   {             
       private Test ()                               Test t = Test.m1();      -------à |/
       {
          …………..
       }
       Public static Test m1 (); -à Factory Method
 }

Real Time Example:

          Thread t = Thread.curentThread ();
   
           String s = String.valueOf (10);

           Class c = Class.forName (“XYZ”);

2. Singleton Java Class:

            A Java class that allows creating only one object per jvm is called singleton java class.

Problem: - Creating multiple objects for java class having same data. It wastes the memory and time of object creation and distraction.

Solution: - Make java class as singleton java class. So that only one java class object will be created and that object can be utilized for multiple number of times.

Rules: -
1.      Class must have a factory method (“static having singleton logic”)
2.      Class must have private constructor

Note: - private constructor is very important in singleton java class to close all the doors of object creation of except throw factory method that contains singleton logic.

Class SingletonTest
{
   private static SingletonTest n = null;

   private SingletonTest()
   {
            System.out.println(“Constructor”);
  }
// Factory method having singletone logic
   public static SingletonTest create()
  {
      //single tone logic
       if(n == null)
        n= new SingletonTest();
       return n;
 }
}

Class Demo
{
    public static void main(String args[])
    {
         SingletonTest.create ();
         SingletonTest.create ();
         SingletonTest.create ();
        SingletonTest.create ();
   }
}

à In single computer we can see multiple jvm’s. When multiple java applications are executing simultaneously or parallel.

>java class name.

Starts JVM process to execute the given java application.

3. Factory Pattern:

            Factory Design pattern all about logic return in a java method to create one of the multiple sub class object based on the data you supplied.

            Ex: - When we don’t know the return object class name while designing any java method we generally take java.lang.Object class as return type. This is nothing but implementing Factory Design Patterns,

       Public Object getAttribute (String name);
 

       session.setAttribute (“name”,”chandra”);

        session.setAttribute (“age”, new Integer (35));

       String s1 = (String) session.getAttribute (“name”);

       Integer i1 = (Integer) session.getAttribute (“age”);

Example:-

//Base Class
Class Person
{
    public String name;
    private String gender;

     public String getName ()
     {
          return name;
     }
     public String getGender ();
     {
          return gender;
      }
 }

//Child class

Class Male extend Person
{
    public Male (String fullName)
    {
          System.out.println (“Hello Mr. “+fullName);
    }
}

Class Female extend Person
{
    public Male (String fullName)
    {
          System.out.println (“Hello Miss “+fullName);
    }
}
//Factory method class

Public Class FactoryTest
{
   public static void main(String args[])
   {
            FactoryTest factory = new FactoryTest ();
 
            Factory.getPerson (args [0], args [1]);
   }
}
public Person getPerson (String name, String gender)
{
   if (gender. Equals (“M”))
   
        return new Male (name);
   else
        return new Female (name);
   else
        return null;
 }
}//end of class

 à In the above code getPerson(------,------) the logic of given based on factory design pattern because it may create one of the Male or Female class object( Sub classes of Person class) based on the data we supplied to the method as argument but no sub class name is mention as return type the supper class. Person to satisfy the requirement of any one sub class object.

4. Abstract Factory:

            It is provides one level abstraction on factory designed pattern. By Isolating the names of several sub classes for whom objects are created based on the data you supplied. So that while working with various logic’s of these sub classes. We need not to know the names of the sub classes.

Example Code:-

Interface ABC
{
    public void xyz ();
}

Class Test1 implement ABC
{
   public Test1()
   {
      System.out.println(“Test1”);
  }
  public void xyz()
  {

      System.out.pringln(“xyz of Test1”);
 }
}//end of class Test1


Class Test2 implement ABC
{
    public Test2()
   {
        System.out.println(“Test2”);
   }
   public void xyz()
   {
      System.out.println(“xyz of Test2”);
   }
}//end of class Test2

Class Demo
{
   public static ABC m1(String name)
   {
       if(name.equals(“a”))
            return new Test1();
       elseif(name.equals(“b”))
            return new Test2();
       else
            return null;
    }
}

//client Code

public Class AbstractFactoryTest
{
     public static void main(String args[])
     {
         ABC Ab1 = Demo.m1(args[0]);
         Ab1.xyz();
     }
}

à In the above client code Demo.m1() returns one of the Test1 or Test2 objects based on the data we supplied at run time but in order to utilize logics of these returned objects we need not to know the class names Test1 and Test2. We can call the logic by just referring objects with interface reference variable that is implemented by both Test1 and Test2 classes.

Q) What is the difference between Factory and Abstract Factory Design Patterns?

R) Factory gives one of the several sub class objects. In order to use logic of any subclass object we must know the name of the subclass. Where as Abstract Factory logic also gives one of the several subclass object based on the input data. We pass but while using logics off these subclass objects we need not to know the names of the concrete class or subclasses.

Abstraction means hiding the implementation details from the client.

5. Proto Type Design Pattern:

            It is the process of creating cloned object of a existing object.

Problem: - If you create duplicate object of existing object manually or separately. It needs lot of JVM resources.

Solution:- Create duplicate object by using clone method of java.lang.object class

            The java object becomes ready for cloning when class of that object implements java.lang.Clonable interface. It is a marker interface because it apple’s special behavior on the object that is making object ready for cloning.

à Implementing proto type design pattern is nothing but creating object through clone.

Class Test implement Clonable
{
    int a,b;
    public Test(int x,int y)
    {

            a=x;
            b=y;
            System.out.println(“constructor “);
     }
     public Object m1()
     {
            try
            {
                        return super. clone();
                    // logic that is implementing proto type design pattern
           }catch(Exception e)
           {
                        e.printStackTrace();
                        return null;
            }
       }
      public String toString()
       {
            return “a= “+ a + “b=” + b;
       }
      public static void main(String args[])
      {
            Test t = new Test(10,20);
            System,out.println(“Data of Object is “ + t.toString());
            Test t1 = (Test)t.m1();
            System.out.println(“Data of object t1 is “+t1.toString());
            t.a =30;
            System.out.println(“Data of object t is “+t.toString());
            System.out.println(“Data of object t is “+t1.toString());
      }//main method close
}//end of the class

6. Builder Design Pattern:-

            The Builder Design Pattern is the process of constructing complex object from simple object step by step but it hides the construction of individual objects in the process of constructing main object. So that the program can create main object are can use logic of main object a without varying about the depended object constructing and their logic.

Ex:-

Interface Item
{
            public int price ();
}
Class Burgger implements Item
{
            public int price ()
            {
                        return 25;
            }
}

Class Frides implements Item
{
            public int price ()
            {
                        return 15;
            }
}

Class Drink implements Item
{
            public int price ()
            {
                        return 30;
            }
}

public Class MealBuilder
{
            public int calcPrice ()
            {
            return new Burger ().price () + new Frides ().price () +new Drink ().price ();
           }
           public static void main (String[] args)
            {
                        MealBuilder ms = new MealBuilder ();
                        Int val = ms.calcPrice ();
                        System.out.println (“Meal Price value “+ val);
            }
}//end of the class

In the above code the calcPrice () of Meal Builder class gives the total meal price by knowing the price of each item that is used in the meal. So that the client is not bothered about knowing price of each item when he ordered a meal. That is nothing but builder design pattern.

7. Template Design Pattern:

            Template means readily available wizard. Instead of calling multiple methods in a sequence by recommending method names to complete a task it is recommended it is recommended to combine all these methods called in one method and use one method to complete the task. This is called Template Design Pattern.


Problem:                                                                      solution:

Task 1   x();                                                      public int xyz()
              Y();                                                     {
              Z()                                                          x();
              A()                                                          y();
              B()                                                          z();
                                                                             A();
                                                                              B();
                                                                         }
Real Time Ex:-  Request Processor class is a helper class for Action Servlet in this class nearly 16 processXXX() are there to process the request coming to Action Servlet actually ActionServlet is called all the 16 methods is sequence by creating object for Request process class to complete request processing. But ActionServlet calles only one method of request process class that is process(), Because this process internally calles 16 processXXX() by becoming template methods.

Processor precess(request, response)

8. Adapter Design Pattern:

            Adapter means taking others responsibility. When class is not interest to provide implementation al the methods available in the interface make your class containing the from adapter class of that interface. So that you will get freedom to just override only those methods in while we are inset in because adapter class provide null method (empty method) definition for all the methods available in the interface,

Ex:- Java.awt.EventWindowAdapter class is an Adapter class for java.awt.Event.WindowListener Interface.

Problem:-

Public interface xyz
{
            public void x();
            public void y();
            public void z();
}

Class Test1 implements xyz
{
             public void x()
            {
                …………..
                …………..
               ……………
            }
            public void y()
            {}
            public void z()
            {}
}


Class Test2 implements xyz
{
            public void z()
            {
                        ……………….
                        ………………
            }
}

Solution:

Public Class Demo implements xyz
{
            public void x();
            public void y();
            public void z();
}

public Class Test1 extends Demo
{
            public void x()
            {          
                        …………….
                        …………….
            }
}

public Class Test2 extends Demo
{

            public void z();
            {
                        ………………….
                        …………………
            }
}

           
9. Value Object (Or) Data Transfer Design Pattern:

            While sending huge amount of data values between two layer’s of project instead of sending these values for multiple number of times as individuals it is for multiple number of times it is recommended to combined all these values into single object than send to another layer. This process is called implementation value object design pattern. This reduces number of round trips between layers and it also becomes easy to recive data and to send data.
            Executing select sql query, getting Result Set object and transferring data of the Result Set object to list data structure like Array List and searching this list data structure to another layer is called Value Object Design Pattern implementation in web 2.0 EJB Communication the EJB sends huge amount of values to web Layer for presentation with the support of the Design Pattern implementation.

            In Struts development application multiple values of a form(View Layer) will be send to Action Class(Model Layer) by combining into single object called into Form Bean class object. This process is nothing but simple dealing with value object Design Patterns.

  1. IOC/DI:

If main object spends time to get dependent values by performing search or lookup operation then it is called dependency lookup.

            Ex;- if servlet or EJB components gets data source object by performing search or lookup operations on naming service using JNDI then it is called dependency lookup. When main object is ready if the under laying frame work or container software automatically assignes depended values to main object then it is called dependency injection or inversion of control. In Struts the way Frame Work Software auto matically written form data to form bean class object by calling setXXX() methods is called DI / IOC.

            Ex:- When Object is created the way JVM executes one of the existing constructer as to assign intial values to object as depended values comes under dependency injestin. The latest frame work software like spring structs and the latest EJB 3.0 are given based on DI.
           

            End of The Creational Design Pattern Here Next post Web Design Patterns Please post comments. So that I can update here.