Pages

Friday, January 7, 2011

Java n J2ee

1. What is abstract class?


Abstract classes are classes that contain one or more abstract methods (methods without implementation). An abstract method is a method that is declared, but doesn't contain implementation (like method declaration in the interface). Abstract classes can't be instantiated, and require subclasses to provide implementations for the abstract methods. This class must be inhertied. This class is mostly used as a base class.

2 . What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.



There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature Interface Abstract class

Multiple inheritance A class may inherit several interfaces. A class may inherit only one abstract class.

Default implementation An interface cannot provide any code, just the signature. An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface. An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity If various implementations only share method signatures then it is better to use Interfaces. If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed Requires more time to find the actual method in the corresponding classes. Fast

Adding functionality (Versioning) If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined



2. What is swing?

Here, you will know about the Java swing. The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc. All AWT flexible components can be handled by the Java Swing. The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window.

Here the following APIs interfaces and classes are available:

The following interfaces and it's descriptions to be used by the Java swing.

Interfaces Descriptions

Action This interface performed the action with the ActionListener where the multiple controls are used for same purposes.

BoundedRangeModel This interface defines the data model of components like: sliders and progressBars.

ButtonModel It defines the state model for the buttons like: radio buttons, check boxes etc.

CellEditor This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditor implements the wrapper based approach.

ComboBoxEditor In this interface, the editor component used to JComboBox components.

ComboBoxModel This interface represents the data model in a list model with the selected items.

DesktopManager This interface has JDesktopPane object. The JInternalFrame implements in the JDesktopPane with the help of DesktopManager.

Icon This interface used to graphical representation of the components. It has fixed size picture.

JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the combo box data model.

ListCellRenderer This interface used for paint the cell in the list with the help of "rubber stamps" .

ListModel This interface used for JList components method. It gets the value of each cell of list.

ListSelectionModel This interface indicates the components, which are stable or not.

MenuElement This interface used where the any components are implements in the menu.

MutableComboBoxModel This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel.

Renderer It defines the requirements of an object for displaying the values.

RootPaneContainer This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc.

Scrollable This interface provides the scrolling to show the large amount of data with the help of JScrollPane.

ScrollPaneConstants This interface used for JScrollPane components.

SingleSelectionModel This interface used to select the one index in a model.

SwingConstants You can set the components on the screen to own requirements.

UIDefaults.ActiveValue It constructs the DefaultListCellRenderer.

UIDefaults.LazyValue This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it using LazyValue.createValue() method.

WindowConstants This interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration.

The following classes and it's descriptions to be used by the Java swing.

Classes Descriptions

AbstractAction This class handles the any types of action and provides JFC Action interface.

AbstractButton This class defines the nature of buttons and menu items.

AbstractCellEditor It provides a list and contents of the data model.

AbstractListModel This class defines the data model which provides the list with its contents.

ActionMap This class works with InputMap and performs any action when the key is pressed.

BorderFactory This class extends from Object and creates the Border instance in the factory.

Box It provides the fixed spaces between two components and uses the BoxLayout object of the layout manager.

Box.Filler This class participates in the Layout and uses the lightweight components.

BoxLayout This class uses the arranging the multiple components either horizontally or vertically. The Box container uses this class.

ButtonGroup This class used to create the multiple buttons in a ButtonGroup object.

CellRandererPane This class used to insert the components like: JList, JTable and JTree.

ComponentInputMap This class has ComponentInputMap constructor and creates the components with the help of InpuMap.

DebugGraphics It extends from the Graphics and used to debug the graphics

DefaultBoundedRangeModel This class provides the implementation of default BoundedRangeModel.

DefaultButtonModel This class implements the generic ButtonModel.

DefaultCellEditor It implements the TableCellEditor and TreeCellEditor for the table and tree cells.

DefaultComboBoxModel It provides the default model for combo boxes.

DefaultDesktopManager It implements the DesktopManager. The DesktopManager has the JInternalFrame for creating the internal fame in a frame.

DefaultFocusManager It provides the implementing the FocusManager.

DefaultListCellRanderer It implements the default ListCellRanderer.

DefaultListCellRanderer.UIResource This extends the DefaultListCellRanderer and implementing in the UIResource.

DefaultListModel It extends the AbstractListModel and implementing the java.util.Vector.

DefaultListSelectionModel This class used for select the list in a data model.

DefaultSingleSelectionModel This class provides the default SingleSelectionModel.

FocusManager It handles all focus like: gainedFocus and lostFocus.

GrayFilter It extends the RGBImageFilter and used for disabling the image through the button.

ImageIcon This class implements the Icon and paints the icons from the images.

InputMap This class uses the ActionMap to performed the action when you press any key of keyboard. It bounds data between the input event and an object.

InputVerifier This class helps you when you works with the text fields through the focus.

JApplet This class extends the Applet and implements the Accessible and RootPaneContainer.

JButton This class extends the AbstractButton and you can create the new button.

JCheckBox This class extends the JToggleButton and implements the check box in which buttons are selected or deselected.

JCheckBoxMenuItem It extends the JMenuItem and determines the items which is selected or deselected.

JColorChooser It extends the JComponent and implementing the Accessable. Here, you choose and manipulate the colors.

JComboBox This class extends the JComboBox. It provides the drop-down list where user select only one item or value at a time. But combo box is a combination of multiple text or buttons etc.

JComponent In java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc.

JDesktopPane This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager.

JDialog It extends the Dialog. This class used to create the dialog window and when you want to create the custom dialog window with the help of JOptionPane method.

JEditorPane This class extends the JTextComponent. It edits the component by the EditorKit.

JFileChooser This class provides the facility to choosing the file.

JFrame It extends the Frame and supports the swing components architecture.

JInternalFrame This class extends from the JComponent and provides the facility to dragging, closing, resizing and menu bar of the internal frame. The JInternalFrame added into the JDesktopPane.

JInternalFrame.JDesktopIcon It displays the desktop icon and create the instance of JInternalFrame and iconify.

JLabel This class used to show the small text and image.

JLayeredPane It has JFC/Swing container that can be used to overlap the components to each other.

JList This class used to create a list where you select the one or more than objects.

JMenu This class used to create a new menu where you add the JMenuItems. When you select the item then shows the popup menu items in the JMenuBar.

JMenuBar It used to create a new menu bar where the JMenu objects are added.

JMenuItem This class used to create new menu items in the mebus.

JOptionPane It used to create some different types of dialog box like: message dialog box, error dialog box etc.

JPanel It extends the JComponent and used to create a new panel.

JPassworkField It provides the single line text editing. Here, don't available the original characters but view type indication characters are available.

JPopupMenu This class used to create a popup menu. It provides small window where the various types of choices are available.

JPopupMenu.Separator Here the popup menu and the separator are available.

JProgressBar It shows the integer types values in percent within a bounded range to determine the working process.

JRadioButton It implements the radio button and shows the state of an item selected or deselected.

JRadioButtonMenuItem It extends the JMenuItem and implements the radio button menu item

JRootPane This class provides the component behind the scenes by JFrame, JWindow, JDialog etc. for providing the task-orientation and functionality.

JScrollBar This class used to create a scroll bar. It provides the view content area where you show the content to scroll this.

JScrollPane It provides the scrollable view components.

JSeparator This class use the separator among the components.

JSlider This class provides a control to represent a numeric value by dragging the slider.

JSplitPane This class used to divides the two components graphically like: top and button, left and right.

JTabbedPane This class provides the tab component through which you can switch from one component to another component regarding to the specific tab button by clicking on that.

JTable It provides the user interface component and represents the two dimensional data.

JTextArea It provides the multi line plain text area.

JTextField It provides the facility to editing the text in a single line.

JTextPane This class provides the component like JTexArea for multiple lines text with more capabalities.

JToggleButton It implements two state button that means selected or deselected.

JToggleButton.ToggleButtonModel It extends the DefaultButtonModel and provides the ToggleButton model.

JToolBar It provides set of command buttons icons that performs the different actions or controls.

JToolBar.Separator It provides the tool bar separator.

JToolTip It shows the tool tips related to it's components.

JTree It shows the data in a hierarchical way.

JTree.DynamicUtilTreeNode This extends the DefaultMutableTreeNode and create children nodes.

JTree.EmptySelectionModel It does not allows the any selection.

JViewPort It gives you about the underlying information.

JWindow It extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons.

KeyStroke This class controls the key events on the keyboard for the equivalent device.

LayoutFocusTraversalPolicy This class conducts the sorting objects according to their size, type, position or orientation.

LookAndFeel It provides the dramatically changes in the component like frame related to the graphics for the application. Through this the application can be done very efficient and easier.

MenuSelectionManager It has menu selection hierarchy.

OverlayLayout The layout manager arrange the components.

ProgressMonitor This class is used to monitoring the progress of any operation to be done.

ProgressMonitorInputStream This class creates a progress monitor to monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed.

RepaintManager This class manage and override the repaint requests.

ScrollPaneLayout It implements the LayoutManager and manage the components like: scroll bar, row header, column header etc.

ScrollPaneLayout.UIResource It extends the ScrollPaneLayout and implements the UIResource.

SizeRequirements It calculates the size and positions of components.

SizeSequence It represents the order list of size and it's positions.

SwingUtilities This class has utilities methods for swing.

Timer Actions perform the predefined rate.

ToolTipManager It manages the all tool tips.

UIDefaults It extends the Hashtable and you set/get the value with the help of UIManager.

UIDefaults.LazyInputMap This class creates a Input Map through it's createValue() method. The array of key after binding is passed to the constructor of this. Example of binding of key is array of pressing key information (e.g. ctrl + c or alt + f).

UIDefaults.ProxyLazyValue This class is used to create a lazy value which is used to delay loading of the class to create instance for that.

UIManager This class has track of the current look and feel details.

UIManager.LookAndFeelInfo This is the nested class of UIManager class i.e. used for getting information about all the look and feels installed with the software development kit.

ViewportLayout It implements the LayoutManager and defines the policy for the layout.



Application server

An application server is an application program that accepts connections in order to service requests, by sending back responses. An application server can run remotely (connected to client through a computer network) or can exist on the same computer where the client application is running. Examples include file server, database server, backup server, print server, mail server, web server, FTP server, application server, VPN server, DHCP server, DNS server, WINS server, logon server, security server, domain controller, backup domain controller, proxy server, firewall, etc.



Application server are developed to support the quick development of the enterprise applications. They provide security and state maintenance with the data base and persistence An application server may be a part of a three tier architecture model. A three tier architecture includes the Client Tier, Middle Tier and the EIS (Enterprise Information System) Tier. It may consists of Presentation Tier (as the GUI interface), Middle Tier as the collection of business logic application and the EIS (Enterprise Information System). The view tier is nothing but the web based graphical user interface to interact with the clients, Middle tier is the combination of web containers and the EJB containers. EIS contains persistence and the database management systems to support the applications. JEE Platform requires database to store the business data. This database is accessible by means of JDBC, JDO or the SQLJ APIs. We can also access the database through enterprise beans, web components and the application client components.

















EJB Container or EJB Server



An EJB container is nothing but the program that runs on the server and implements the EJB specifications. EJB container provides special type of the environment suitable for running the enterprise components. Enterprise beans are used in distributed applications that typically contains the business logic. The container performs the various tasks few of them are illustrated below:

Transaction Management: EJB container allows you for transaction management that enables the transaction services, a low level implementation of transaction management and coordination. Container uses the Java Transaction APIs to expose the transaction services. JTA, a high level interface is used to control transactions.

Security: JSE mainly focuses on how to become the environment more secure. Enterprise beans add this feature to provide transparent security so that access to the beans can be made secure just by applying the security attributes rather than coding against the security API.



Resource and Life Cycle Management: EJB container manages the resources like database connections, threads and socket on behalf of enterprise beans. Container creates, destroys, registers the objects and also activates and passivates them. The container is also capable of reusing them whenever required.



Remote Accessibility: A client on the remote machine containing JVM can invoke an enterprise bean running on the host machine. To support the remote accessibility the container uses the remote procedure call technology. When the software is developed by using the OOPs concept then Remote procedure call (RPC) may be referred to as Remote Method Invocation (RMI).



Concurrency Control: Concurrency control is necessary to know the basics of collisions and type of collisions that can occur. If you are not interested to occur them then you can bypass them later they will cause to create problems. So try to detect and resolve them. To do so the EJB Container supports for various types of concurrency controls. First we will concentrate on collision and then techniques to resolve these collisions.



Collision: A collision can occur when two or more transactions tries to change the entities within a system of records. There are three types through which two

or more activities may interfere:

• Dirty read

• Non Repeatable read

• Phantom read

Control mechanism: Mainly two mechanism are used to control the concurrency.

• Optimistic Locking

• Pessimistic Locking

Clustering and load-balancing: Clustering is the process of combining the multiple peripherals, computers and other resources into a single unit. A clustered system then works as load balanced system. In a distributed system when a request is send to the server, an algorithm running on the server decides which server has less load and sends the request to that server. EJB container encapsulates these features to provide smooth and efficient service.



Enterprise Beans



Enterprise beans are the Java EE server side components that run inside the ejb container and encapsulates the business logic of an enterprise application. Enterprise applications are the software applications developed intended to use at large scale. These applications involves large number of data accessing concurrently by many users. Enterprise beans are used to perform various types of task like interacting with the client, maintaining session for the clients retrieving and holding data from the database and communicating with the server.

Benefits of enterprise beans: Enterprise beans are widely used for developing large and distributed applications. EJB container provides the system-level services (like transaction management and security authorization) to the enterprise beans. These services simplifies the development process of large and distributed applications and the developer just have to concentrate on solving the problem occurred in it.

The client developer can focus only on the representation style of the client as all the business logic of the application is contained in the enterprise beans. The client developer does not bother about the code that implements business logic or the logic to access the databases. This means that the clients are thinner. It benefits the client to be thin because the client runs on the small devices.

Developing new applications from the existing beans is much easier because the enterprise beans are portable components. That means applications developed by using the enterprise components can run on any complaint J2EE server.

When to use the enterprise beans: Some of the points are illustrated below that signifies the use of enterprise beans.

• Applications developed by using the enterprise beans deal with a variety of clients, simply by writing few lines of code, so that the client can locate the enterprise beans. The client locating the enterprise bean may be various, numerous and thin.

• Enterprise beans support transaction to ensure the integrity of the database. Transaction is the mechanism of managing the concurrent access of shared objects.

• Managing the fast growing number of users requires distributed application components across multiple machines means that the application must be scalable.

Types of enterprise beans: EJB 3.0 defines two types of enterprise beans. These are:

1. Session bean: These types of beans directly interact with the client and contains business logic of the business application.

2. Message driven bean: It works like a listener or a consumer for a particular messaging service such as Java Message API or JPA for short



Features of EJB 3.0

Now its time to look over the new features of EJB 3.0 that provides some simplification over the previous EJB API. There are various simplification made in EJB 3.0 like:

• No need of home and object interface.

• No need of any component interface.

• Made use of java annotations.

• Simplifies APIs to make flexible for bean's environment.

Now we will discuss all the above aspects of EJB3.0 that makes the EJB programming model simple and more efficient.

Elimination of Home and Remote Interfaces: Deprecation of home and remote interfaces simplifies the development. The new session beans contain all the business methods inside the business interface. The bean provider designates the business interface as local business interface or the remote business interface or both according to the client whether it is local or remote. Business methods on remote interface can throw arbitrary application exceptions, while they are not allowed to throw java.rmi.RemoteException. While in case of EJB 2.1 all the methods of home and object interface throws the java.rmi.RemoteException. Package javax.ejb.EJBException encapsulates exceptions such as protocols, system level problems, or otherwise that the container returns to the client. Since EJBException is the subclass of the java.rmi.RemoteException therefore we did not include it in throws clause of business methods.

A message driven bean does not need to include the business interface as there is no direct interaction of the client with the message driven bean. Whenever a MDB has an unexpected problem then the container logs the error and communicate it with the help of javax.ejb.EJBException to the corresponding resource adapter rather than the client.

Elimination of Component Interface: Component interface in EJB2.1 or in earlier versions are used to provide a way through which the container notifies the bean instances of various life cycles they are affecting it. The previous versions of the component interface are used to stay in the events in its lifecycle. These component interfaces includes the various life cycles methods implemented by the bean class. The container used to call the appropriate method of the component interface to handle the bean's instance life cycle events according to the way it wants.

For example, the container notifies the message driven bean instance that it is about to destroy, simply by invoking ejbDestroy() method on the corresponding class of the message driven bean. Bean class can close the JDBC database connection within the ejbDestroy() method to free up the resources. Similarly the container that is going to associate a client in case of stateful notifies the bean instance by calling the ejbCreate() method on the bean class and the bean class instantiates the bean instance. Consider the situation, when the bean does not receive the notification from the container about its life cycle's methods then the bean has to implement the component interfaces regardless whether it is needed or not. In case of session bean, the bean class does not need to implement the javax.ejb.SessionBean or javax.ejb.MessageDrivenBean in case of message driven bean.

Now the next question that arises is that how a bean class get notified by the container if it is interested? The solution is that there are two ways to do so, the first one is, the bean provider can implement a separate bean class that consists of all the callback notification methods that inform the container to treat it as a listener class. The second way is that, a bean provider can implement the notification method inside the bean class and designate this method to handle the corresponding events In both the cases bean class uses annotations. Annotations are the additional key features of EJB 3.0 specifications. To know about the annotation just click on the link annotations.

Simplified Access to Environment: Almost all the EJBs are required to access the environment to gain access to external resources, enterprise beans and other entries like properties. To get hold of these entries EJB mainly relies on JNDI API. EJB 3.0 also includes the features like lookup method on the EJBContest and dependency injection to access the bean's dependencies.



Dependency Injection: Dependency injection is the mechanism through which the container injects the requested environmental entry to make available to the bean instance before any bean instance is invoked on that particular instance. Then the container injects these entries into bean variables or methods. It is bean provider's duty to tell the container that which method or variables should be injected at runtime. The bean provider can do this by using the deployment descriptor or annotations. Bean methods used for dependency injection should follow the java naming convention for properties in that they should follow the setXXX() convention.

Consider the situations like dependency injection fails due to some reasons, the container can not make available the environmental entries due to which the bean is functioning properly, in such situations the container discards the bean instances and creates new instances.

EJB Context: Bean must know about its environment at runtime such as security principle, transaction context in which its method is invoked and so on. javax.ejb.EJBContext API works like a window for the bean to the outside world through which it is interacting to the container. EJBContext is further categorized into SessionContext and MessageDrivenContext for the session beans and message driven beans respectively. Bean instances may use the dependency injection to access EJBContext instance. Another way through which a JNDI accesses the environment variables is the lookup() method of the EJBContext interface. Bean must use the JNDI API to access the environmental dependencies.

Enhanced Lifecycle Methods and Callback Listener Classes: EJB 3.0 does not enforce to implement all unnecessary callback methods but can designate any other method to receive the notification for life cycle events. We can also use the callback listener class instead of callback methods defined in the same bean class.

Interceptors: An intercept is a method used to intercept a business method invocation. Stateless session beans, Stateful session beans and message driven beans may includes the interceptors. We can also define an interceptor class instead of defining the interceptor methods in the bean class.

Simple JNDI lookup of EJB: Lookup of the EJB has been simplified so that the client can directly invoke methods on EJB rather than creating the bean instance simply by invoking create method on EJB.



Annotations



Sun Microsystem added the features like annotation to make the development easier and more efficient in jdk 5. The main objective to develop the annotations is to make the development easier. Annotations behaves like the meta. The literal meaning of meta data is data about data. Java also signifies this meaning. Annotations are like meta data, means you are free to add your code and can also apply them to variables, parameters, fields type declarations, methods and constructors. Metadata is also used to create the documentation to perform rudimentary compile time checking and even for tracking down the dependencies in code. XDoclet contains all these features and is widely used. Annotations provide a means of indicating about methods, classes, dependencies, incompleteness and also about the references on other methods and classes respectively. Quoting from Sun's official site, "It (annotation-based development) lets us avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a declarative programming style where the programmer says what should be done and tools emit the code to do it."

Annotation is the way of associating the program elements with the meta tags so that the compiler can extract program behavior to support the annotated elements to generate interdependent code when necessary.

Fundamentals of annotations

While going through the annotations you should consider two things. The first one is the "annotation" itself and second one is the "annotations types". An annotation is the meta tag, used to give some life to the code you are using. While annotation type is used to define annotations so that you can use them while creating your own custom annotations.

An annotation type definition appends an "at" @ sign at the start of the interface keyword with the annotation name. On the other hand, an annotation includes the "at" @ sign followed by the annotation type. You can also add the data within the parenthesis after the annotation name. Lets illustrate the concept more clearly by using some examples.

Defining an annotation (Annotation type)

public @interface Example {

String showSomething();

}

Annotating the code (Annotation)

Example (showSomething="Hi! How r you")

public void anymethod() {

....

}

Annotation Types: Three types of annotations types are there in java.

• Marker: Like the marker interface, marker annotations does not contain any elements except the name itself. The example given below clarifies the concept of marker interface.

Example:

public @interface Example{

}

Usage:

@Example

public void anymethod() {

------------

}

• Single-value: This type of elements provide only single value. It means that these can be represented with the data and value pair or we can use the shortcut syntax (just by using the value only within the parenthesis).

Example:

public @interface Example{

String showSomething();

}

Usage:

@Example ("Hi ! How r you")

public void anymethod(){

--------

}

• Multi-value or Full-value: These types of annotations can have multiple data members. Therefore use full value annotations to pass the values to all the data members.

Example:

public @interface Example{

String showSomething();

int num;

String name;

}

Usage:

@Example (showSomething = "Hi! How r you", num=5, name="zulfiqar" )

public void anymethod{

// code here

}

Rules defining the Annotation type: Here are some rules that one should follow while defining and using annotations types

• Start the annotation declaration starting with the symbol "at" @ following the interface keyword that should follow the annotation name.

• Method declaration should not throw any exception.

• Method declaration should not contain any parameter.

• Method using annotations should return a value, one of the types given below:

• String

• primitive

• enum

• Class

• array of the above types

Annotations: JDK 5 (Tiger) contains two types of annotations:

• Simple annotations: These types of annotations are used to annotate the code only. We can not use these types of annotations for creating the custom annotation type.

• Meta annotations: Also known as annotations of annotations are used to annotate the annotation-type declaration.

Simple annotations: JDK 5 includes three types of simple annotations.

• Override

• Depricated

• Suppresswarnings

JDK 5 (also known as Tiger) does not include many built-in annotations but it facilitates to core java to support annotation features. Now will discuss in brief each of the above simple annotation types along with examples.

Override annotation: The override annotation ensures that the annotated method is used to override the method in the super class. If the method containing this type of annotation does not override the method in the super class then the compiler will generate a compile time error.

Lets take an example and demonstrate what will happen if the annotated method does not override the method in the super class.

Example 1:

public class Override_method{

@Override

public String toString(){

return super.toString() +

"Will generate an compile time error.";

}

}

Suppose there is spell mistake in the method name such as the name is changed from toString to toStrimg. Then on compiling the code will generate the message like this:

Compiling 1 source file to D:tempNew Folder (2)

TestJavaApplication1buildclasses

D:tempNew Folder (2)TestJavaApplication1srctest

myannotationTest_Override.java:24: method does not override

a method from its superclass

@Override

1 error

BUILD FAILED (total time: 0 seconds)

Deprecated annotation: These types of annotations ensure that the compiler warns you when you use the deprecated element of the program. The example given below illustrates this concept.

Example: Lets first create the class containing the deprecated method.

public class Deprecated_method{

@Deprecated

public void showSomething() {

System.out.println("Method has been depricated'");

}

}

Now lets try to invoke this method from inside the other class:

public class Test_Deprication {

public static void main(String arg[]) throws Exception {

new Test_Deprication();

}

public Test_Deprication() {

Deprecated_method d = new Deprecated_method();

d.showSomething();

}

The method showSomething() in the above example is declared as the deprecated method. That means we can't further use this method any more. On compiling the class Depricated_method does not generate any error. While compiling the class Test_Deprication generates the message like this:

Compiling 1 source file to D:tempNew Folder

(2)TestJavaApplication1buildclasses

D:tempNew Folder

(2)TestJavaApplication1srctestmyannotation

Test_Deprication.java:27:

warning: [deprecation] showSomething() in

test.myannotation.Deprecated_method has been deprecated

d.showSomething();

1 warning

The Suppresswarning annotation: These types of annotations ensure that the compiler will shield the warning message in the annotated elements and also in all of its sub-elements. Lets take an example:

Suppose you annotate a class to suppress a warning and one of its method to suppress another warning, then both the warning will be suppressed at the method level only. Lets demonstrate it by an example:

public class Test_Depricated {

public static void main(String arg[]) throws Exception {

new TestDepricated().showSomething();

}

@SuppressWarnings({"deprecation"})

public void showSomething() {

Deprecation_method d = new Deprecation_method();

d.showSomething();

}

}

This example is suppressing the deprecation warnings that means we can't see the warnings any more.

Note: Applying annotation at most deeply nested elements is a good idea. It is better to apply annotations at the method level rather than the class to annotate a particular method.

Meta-Annotations (Annotation Types): There are four types ofm Meta annotations (or annotations of annotations) defined by the JDK 5. These are as follows:

• Target

• Retention

• Documented

• Inherited

Target annotation: Target annotation specifies the elements of a class to which annotation is to be applied. Here is the listing of the elements of the enumerated types as its value:

• @Target(ElementType.TYPE)—applicable to any element of a class.

• @Target(ElementType.FIELD)—applicable to field or property.

• @Target(ElementType.PARAMETER)—applicable to the parameters of a method.

• @Target(ElementType.LOCAL_VARIABLE)—applicable to local variables.

• @Target(ElementType.METHOD)—applicable to method level annotation.

• @Target(ElementType.CONSTRUCTOR)—applicable to constructors.

• @Target(ElementType.ANNOTATION_TYPE)—specifies that the declared type itself is an annotation type.

Here is an example that demonstrates the target annotation:

Example:

@Target(ElementType.METHOD)

public @interface Test_Element {

public String doTestElement();

}

Now lets create a class that use the Test_Element annotation:

public class Test_Annotations {

public static void main(String arg[]) {

new Test_Annotations().doTestElement();

}

@Test_Target(doTestElement="Hi ! How r you")

public void doTestElement() {

System.out.printf("Testing Target Element annotation");

}

}

The @Target(ElementType.METHOD) specifies that this type of annotation can be applied only at method level. Compiling and running the above program will work properly. Lets try to apply this type of annotation to annotate an element:

public class Test_Annotations {

@Test_Target(doTestElement="Hi! How r you")

private String str;

public static void main(String arg[]) {

new Test_Annotations().doTestElement();

}

public void doTestElement() {

System.out.printf("Testing Target Element annotation");

}

}



Here we are trying to apply @Target(ElementType.METHOD) at the field level by declaring the element private String str; after the @Test_Target(doTestElement="Hi ! How r you") statement. On compiling this code will generate an error like this:

"Test_Annotations.java":

D:R_AND_DTest_Annotationsrctestmyannotation

Test_Annotations.java:16:

annotation type not applicable to this kind of declaration at line

16, column 0

@Test_Target(doTestElement="Hi ! How r you")

^

Error in javac compilation

Retention annotation: These types of annotation specify where and how long annotation with this types are to be retained. There are three type of Retention annotations are of three types.

• RetentionPolicy.SOURCE: This type of annotation will be retained only at source level and the compiler will ignore them.

• RetentionPolicy.CLASS: This type of annotation will be retained at the compile time the virtual machine (VM) will ignore them.

• RetentionPolicy.RUNTIME: Virtual machine will retained the annotation of this type and they can be read only at run-time.

Lets demonstrate that how this type of annotations are applied by taking an example using RetentionPolicy.RUNTIME.

Example:

@Retention(RetentionPolicy.RUNTIME)

public @interface Retention_Demo {

String doRetentionDemo();

}



This example uses the annotation type @Retention(RetentionPolicy.RUNTIME) that indicates the VM will retained your Retention_Demo annotation so that it can be read effectively at run-time.

Documented annotation: This type of annotation should be documented by the javadoc tool. javadoc does not include the annotation by default. Include the annotation type information by using @Documented in the generated document. In this type of annotation all the processing is done by javadoc-like tool.

The given example demonstrates the use of the @Documented annotations.

Example:

@Documented

public @interface Documented_Demo {

String doTestDocumentedDemo();

}



Next, make changes in Test_Annotations class as follows:



public class Test_Annotations {

public static void main(String arg[]) {

new Test_Annotations().doTestRetentionDemo();

new Test_Annotations().doTestDocumentedDemo();

}

@Retention_Demo (doTestRetentionDemo="Hello retention annotation")

public void doTestRetentionDemo() {

System.out.printf("Testing 'Retention' annotation");

}

@Documented_Demo (doTestDocumentedDemo="Hello Test documentation")

public void doTestDocumentedDemo() {

System.out.printf("Testing 'Documented' annotation");

}

}

Inherited Annotation: This annotation is little bit complex. It inherits the annotated class automatically. If you specify @Inherited tag before defining a class then apply the annotation at your class and finally extend the class then the child class inherits the properties of the parent class automatically. Lets demonstrate the benefits of using the @Inherited tag by an example:

Example:

Lets first, define the annotation:



@Inherited

public @interface ParentObjectDemo {

boolean isInherited() default true;

String showSomething() default "Show anything?";

}



Now, annotate the class with our annotation:



@ParentObjectDemo

public Class ChildObjectDemo {

}

The above example shows that you do not need to define the interface methods inside the implemented class. The @Inherited tag automatically inherits the methods for you. Suppose you define the implementing class in the old-fashioned-java-style then let us see the effect of doing this:

public class ChildObjectDemo implements ParentObjectDemo {

public boolean isInherited() {

return false;

}

public String showSomething() {

return "";

}

public boolean equals(Object obj) {

return false;

}

public int hashCode() {

return 0;

}

public String toString() {

return "";

}

public Class annotationType() {

return null;

}

}

Have you seen the difference? You have to implement all the methods of the parent interface. You will have to implement the equals(), toString(), and the hashCode() methods of the Object class and also the annotation type method of the java.lang.annotation.Annotation class. You will also have to include all these methods in your class regardless of whether you are implementing all these methods or not.

No comments:

Post a Comment