Thursday 30 January 2014

Annotations in action


Annotations is not new to JEE programmer, we are often using annotation while coding in spring or hibernate or simple servlet-3 or  EJB-3. Day by dat the popularity of annotations goes increasing. One line annotation can reduce 10 line of XML configuration.In other word the popularity of java is because of annotation.

So before using annotations we should know and understand it better.This blog will cover  what is annotation how to use it effectively and how to create and use your own custom annotation.

At the end of session we attached some source code of spring-MVC related annotation like @Controller, @ResuestMapping etc.

What is Annotation?

Java annotations are used to provide meta data for Java code, data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Uses/Purposes of annotation:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

Create your custom annotation:

It is possible to create your own annotations. Annotations are defined in their own file, just like a Java class or interface. Here is an example:

@interface MyAnnotation {

    String     value();
    String      name();
    int           age();
    String[]   newNames();


This example defines an annotation called MyAnnotation which has four elements.
Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.
To use the above annotation, you do like this:

    newNames={"Jenkov", "Peterson"}
public class MyClass {

As you can see, I have to specify values for all elements of the MyAnnotation annotation.

Annotation Default Values:

You can specify default values for an element. That way the element becomes optional and can be left out. Here is an example of how the annotation definition looks with a default value for an element:
@interface MyAnnotation {

    String   value() default "";

    String   name();
    int      age();
    String[] newNames();

The value element can now be left out when using the annotation. If you leave it out, it will be considered as if you had used the default value for the value element. Here is an example:
    newNames={"Jenkov", "Peterson"}
public class MyClass {

Notice that the value element is no longer present.


You can specify for your custom annotation if it should be available at runtime, for inspection via reflection. You do so by annotating your annotation definition with the @Retention annotation. Here is how that is done:
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


@interface MyAnnotation {

    String   value() default "";

Notice the annotation added above the MyAnnotation definition:
This is what signals to the compiler and JVM that the annotation should be available via reflection at runtime. Accessing annotation at runtime is covered in my Java Reflection and Annotations tutorial, which is part of my Java Reflection Tutorial.
The RetentionPolicy class contains two more values you can use:
RetentionPolicy.CLASS means that the annotation is stored in the .class file, but not available at runtime. This is the default retention policy, if you do not specify any retention policy at all.
RetentionPolicy.SOURCE means that the annotation is only available in the source code, and not in the .class files and not a runtime. If you create your own annotations for use with build tools that scan the code, you can use this retention policy. That way the .class files are not poluted unnecessarily.


You can specify which Java elements your custom annotation can be used to annotate. You do so by annotating your annotation definition with the @Target annotation. Here is an example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

public @interface MyAnnotation {

    String   value();
This example shows an annotation that can only be used to annotate methods.
The ElementType class contains the following possible targets:
Most of these are self explaining, but a few are not. Therefore is here an explanation of the few that are not obvious.
The ANNOTATION_TYPE target means annotation definitions. Thus, the annotation can only be used to annotate other annotations. Like the @Target and @Retention annotations.
The TYPE target means any type. A type is either a class, interface, enum or annotation.


The @Inherited annotation signals that a custom annotation used in a class should be inherited by subclasses inheriting from that class. Here is an example:


public @interface MyAnnotation { }

public class MySuperClass { ... }
public class MySubClass extends MySuperClass { ... }

In this example the class MySubClass inherits the annotation @MyAnnotation because MySubClass inherits from MySuperClass, and MySuperClass has a @MyAnnotation annotation.


The @Documented annotation is used to signal to the JavaDoc tool that your custom annotation should be visible in the JavaDoc for classes using your custom annotation. Here is an example:

public @interface MyAnnotation {


public class MySuperClass { ... }
When generating JavaDoc for the MySuperClass class, the @MyAnnotation is now included in the JavaDoc.
You will not use the @Documented annotation often, but now you know it exists, if you should need it.

Spring related annotation:

Source code for @RequestMapping:


@RequestMapping(value = {"/markcompleted","/updateinteractionbyuniqueid"},method = {RequestMethod.POST,RequestMethod.GET})

Source code:


For more spring related annotation you can form the spring source code form Github

Saturday 4 January 2014

All About Object


In an object oriented environment like java it's a common requirement to create object(instantiating a class), which is the basic building block. So we have to know the object better before creating and using them.

In a complex object oriented environment lot's of object will be there. Each object will have some role and responsibility, it's as simple as team work. For example DAO, BO, DTO etc. A DAO acronym as data access object, only know how to communicate with back-end which may not known to BO(Business object) because BO will have some different role and responsibility and so on.

This blog will explain you what is the necessity of creating a object, what happens internally when we are creating object. How many different way's are there to create object in java etc.

How an Object is different from a Class!!!

It seems lot's of professional is having same doubt and many of them are thinking that both object and class are same.

Conceptually both are different. A class is a blueprint to create object, there is no existence of class without object in other word object is representing a class.

For instance consider Animal. In particular there is nothing called animal it's just a common terminology which indicates to a group or category or class of leaving being.If I will tell dog or cat then it's existing and you can feel yes dog or cat is a prototype of an animal and in this case dog is an Object which represents Animal class.

So under a class we can create lot's of Object where as vice-versa is not applicable conceptually.
Hope you got a clear picture about object and class.

Does object and instance are same in java

Here we will discuss how object and instance are related as per java is concerned. 
Technically instance is a variable to hold an object. In other word instance is a handler for object.

          ABC  instance1 = new ABC();

 here ABC  >> is class, 
[new ABC();] >>as a whole it is a object 
instance1 >> is a instance or variable of type(user defined datatype) ABC.

In the above case new ABC()  is enough to create a object, technically we don't need  ABC  instance1  but for further use we have to store/assign the state of object to a particular instance/variable because in java each and every object is unique. later on we will discuss about this (hashcode, hashvalue etc).
In common practice you can consider instance is a alias for object hence both are same as per java is concerned different story for c and cpp.

Take the advantage of instanceof operator:

instanceof is a keyword using which you can able to check whether an instance is belongs to a particle object or not.

Why and when to create Object?

Basically in programming we are using lot's of veritable and blocks. Each veritable and block need some amount of memory. Memory is a resource of operating system so as a java programmer we don't have direct access to memory, it's highly encapsulated.

JVM is allocated few amount of RAM based on OS specification which is well know as runtime area and all static and non static member will use this based on demand and requirement. 

As per class member is concerned, we can divide the memory allocation into two parts. First one is Static members which will allocation memory while class loading by class-loader itself(an operation done by JVM to make the programme into process, if you want then you can implement your custom class loader) .

Then second one is allocating memory to non-static member, where we have to create object for allocating memory, in other word we will allocate  memory on demand dynamically. So the benefit is, no need to load all the member statically  like "C programming" because we may not use all member at time so unnecessarily it's wasting of memory which can be used by some other resource.

Object Internals/How Object works:

From previous discussion we came to know that, to assign memory dynamically we need to create object. But now question arises how the internal process is carried out and what actually happens Technically.

Brilliant question, we have answer for your question. OK to understand the answer you have to know your constructor better(We are assuming you have basic knowledge about Inheritance).

Role of Constructor  on Object Creation:

Not to forget, as per  java is concerned, the super class of all class is Object class, in simple if a class doesn't extends any class then by default it extends Object class.

For example i can write>> class A{...} equivalent to Class A{...} extends Object{...}

OK before proceeding further about "role of constructor on object creation" please solve the following debugging problem.

If you could observe the above programme then you must got the following output

You must wander by looking at the output.
Yes whenever you are creating object you are calling the constructor. In the above  snippet

      ObjectAndConst objectandConst = new ObjectAndConst();

ObjectAndConst() means we are calling to a constructor. if already a constructor is there then jvm will pick that one or else default constructor will come into action.

While creating object for a class first it will call to that particular class constructor and as you know that the first line of each and every constructor is super keyword as hidden hence it will call to the super class constructor.

In our case ObjectAndConst class's super class is ObjectAndConstBase and again ObjectAndConstBase will call to Object class constructor(super class of all class is object class if that class doesn't not extends any class). After completely executing the object class constructor the control will come to calling place i.e ObjectAndConstBase class and it will execute the rest of code and again the control will call back to ObjectAndConst as the execution started form that place. 

In this whole process we are not only creating Object of ObjectAndConst class rather we are creating 3 object, first one is for Object class which will create first, second one is ObjectAndConstBase and finally ObjectAndConst which mean we create 3 different object(chain of Object) and assign to the instance of ObjectAndConst class

Different possible way to create Object:

There are several different way to create object, here we will discuss 5 different way of creating object

1. Using new keyword

    This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.

    ABC object = new ABC();

2. Using Class.forName()

    If you know the name of the class & it has a public default constructor we can create an object in this way.

     ABC object = (ABC) Class.forName("").newInstance();

 3. Using clone()

    The clone() can be used to create a copy of an existing object.

    ABC anotherObject = new ABC(); 
    ABC object = anotherObject.clone();

4. Using object deserialization

   Object deserialization is nothing but creating an object from its serialized form.

   ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
   ABC object = (ABC) inStream.readObject();

5. Using factory method

    Basically we are using this object creation method in  singleton designing pattern where we can't 
    directly create one object using new operator inter one static method will be there which will create 
    object and return the class instance which  is known as factory method.


I know you will have lot's of question in your mind. It's not feasible to write everything in a single post. So gradually we will add post by post. Feel free to comment in case of any question or suggestion.
Hope you enjoyed :)