Sunday, October 13, 2013

Java Annotations

An annotation is a metadata about a Java program; it gives information about the program. It has no direct impact on the program but it can be used later for complementing the program. This feature is one of the fundamental change to the language in Java SE5. The syntax of annotation is quite simple; the language just added @ symbol to achieve it. The at sign (@) indicates to the compiler that what follows is an annotation.

     @override
     public String toString(){
           //override method
      }

Annotations are just like other modifiers like public, static, void etc. 

Why Annotations

Let's take an example of ORM tools (like Hibernate) which map plain java classes to database tables. One simple approach which has been followed traditionally is, to provide a separate XML config file for mapping. So once a Java class is written by a developer, he should write a corresponding XML descriptor file. And in the descriptor file, developer will be binding class name to the table name and similarly class attributes to the table columns. The bean class, as well as XML descriptor file, should be in sync.  This is an extra overhead for the system as well as developer. Annotations allow you to get rid of this extra overhead and provide all mapping details in the bean class itself with very little overhead. It can also be used to get rid of writing some repetitive code. 


Java SE5 built-in Annotations

Java SE5 contains three general purpose built-in annotations :
  1. @Override: indicates to the compiler that the method definition needs to be overridden in the subclass. It is not mandatory but if used it can help detect errors at compile time ( in case if you are not overriding the method properly)
  2. @Deprecated: indicates that the marked element is deprecated and should not be used. If you use a  class, method or field with @Deprecated annotation; compiler generates the warning. 
  3. @SuppressWarnings: used to turn off a specific compiler warning. If you use a deprecated method then the compiler usually generates a warning; which could be eliminated by using this annotation. 


Creating Annotations

Annotations are just like regular Interfaces; with only exception that it can take a default value. Annotations get compiled like regular classes, and if you use any annotation, the compiler ensures that the definition of the same is available in your build path. Let's take a look:

   //Developer annotation    
   public @interface Developer{
          String name();   //element
    }
   
   //TimeToRun annotation with default value 
   public @interface TimeToRun{
          int count() default = 1;  //element with default value
    }

I have defined two annotations above. So, quite logically, if you using above annotations; its definition has to be in the build path. 


Using Annotation

Using annotation is quite easy. You would have definitely come across code where built-in annotation like @override would have been used. Now let's see an example where I would be using custom annotations which has been defined above section. 


   public class AnnotationTest {

    @TimeToRun(count= 3)

    public void method1(){

     //invoke this method 3 times

     System.out.println(" method1 invocation ....3 times..");

     }


    @TimeToRun 
    public void method2(){
          //invoke only once which is default value
       System.out.println(" method2 invocation...1 time");
      }
     }

I have used TimeToRun annotation in two methods. Annotations usually contain elements to specify values. In first method, element takes value of 3 and in second method it takes default value (i.e. 1). So providing element value is optional here.
An annotation without any element, is called as marker annotation.


Making Sense out of Annotations 

So far I have created and used Annotations.  So far, it is cool !
But that's NOT end of life !

The real meaning is still missing. This is one of the important aspect; TimeToRun annotation declared in AnnotationTest.java  will be of no use if there is no logic to interpret it. So, we need to write a utility to process annotations and justify their existence. Along with definition of annotation you need a separate tool to parse and understand annotations embedded in source code. This is done through Java's reflection API. I have reserved a separate post to discuss the same in detail (link).

Meta-annotations

So as the title suggests; meta-annotations are annotations which are used for annotating the annotations. Meta-annotations are required for providing scope to annotations. Annotations can be applied on methods, classes, at compile time, during running program etc. So meta-annotation are used for such purposes. Let cover them :

  • @Target – specifies the type of element this annotation can be applied to.
    • ElementType.TYPE- Class, interface (including annotation) or enum declaration
    • ElementType.FIELD- field or property declaration ( including enums )
    • ElementType.METHOD- method level annotation
    • ElementType.PARAMETER- applied to parameter declaration of a method
    • ElementType.CONSTRUCTOR- constructors declaration 
    • ElementType.LOCAL_VARIABLE- local variable declaration
    • ElementType.ANNOTATION_TYPE-indicates that the declared type itself is an annotation type
  • @Retention – specifies how long the annotation information is kept
    • RetentionPolicy.SOURCE—Retained only at the source level and will be descarded by the compiler
    • RetentionPolicy.CLASS—Retained by the compiler at compile time, but will be ignored by the VM
    • RetentionPolicy.RUNTIME—Retained by the VM so they can be read only at run-time reflectively 
  • @Documented – by default annotations are mentioned in java doc, this meta-annotation will make this annotation to be mentioned.
  • @Inherited – Allows subclasses to inherit parent annotation. 
So whenever you use annotation in your program; you should also provide their scope through meta-annotations. 

Saturday, October 5, 2013

Handling Global Variables in Ext JS

Classes don't exist in JavaScript but Ext JS does a fine job in emulating classes as found in object oriented programming languages. This means everything in Ext JS is a class and these classes mostly fall in either of these categories; Model, View, Controller, and Store. So if you could map any new class to either of these category, things fall in place nicely. Now what if something don't fall in either of these ?

What if you need to move common labels and constants to a separate class. If you are writing plain JavaScript then it's quite trivial but NOT so obvious in Ext JS. Let's figure out how to handle labels or common variables in Ext JS.

Singleton Class

Ext JS has support for singleton classes. By definition, singleton can't be instantiated more than once. Global or common variables can be created using a singleton class.

     Ext.define("App.Constants", {
             singleton  : true,  
             
             BASE_URL : "http://localhost:8080/",
             LABLE_HEADER : "geekrai.blogspot",
             TIMEOUT : 6000
     });

Please, note that, singleton property is set to true. That's all we need to do to convert a class into a singleton class. You can test if it's indeed a singleton by creating an instance of above class :

      Ext.create("App.Constants"); //Throws error

Global variables are added in class as key value pair. Save above content in file Constants.js. File can be created at same level as other packages like model, view etc.

Accessing Constants in Application

Above class needs to get loaded in application to successfully access properties mentioned above. As it holds some of the global variables so ideal place will be to load it inside app.js.

     Ext.application({  
           // include model, view, controller etc.

           requires: ['App.Constants']

     });

Now we are good to access variables in any class as App.Constants.<KEY>.
console.log(App.Constants.TIMEOUT);


*** You can also use Ext JS singleton to create utility classes.