<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Java 5.0</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/java-5-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Sun, 16 Jun 2013 11:17:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Implementing a Producer-Consumer scenario using BlockingQueue in Java</title>
		<link>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/</link>
		<comments>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/#comments</comments>
		<pubDate>Wed, 27 Jun 2012 10:00:47 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[java concurrency]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4486</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Before we start with the actual example, lets have a look at the few concepts we should be aware of. Producer-Consumer Problem Wikipedia here says that: The consumer producer problem (also known as the bounded-buffer problem) is a classical example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>Before we start with the actual example, lets have a look at the few concepts we should be aware of. </p>
<h4>Producer-Consumer Problem</h4>
<p>Wikipedia <a href="http://en.wikipedia.org/wiki/Producer-consumer_problem" target="_blank">here</a> says that:<br />
The consumer producer problem (also known as the bounded-buffer problem) is a classical example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer&#8217;s job is to generate a piece of data, put it into the buffer and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. The problem is to make sure that the producer won&#8217;t try to add data into the buffer if it&#8217;s full and that the consumer won&#8217;t try to remove data from an empty buffer.</p>
<p>The solution for the producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be reached by means of inter-process communication, typically using semaphores. An inadequate solution could result in a deadlock where both processes are waiting to be awakened. The problem can also be generalized to have multiple producers and consumers.</p>
<p>There are numerous ways to solve a Producer-Consumer problem and in this post I will show one simple way to solve this problem by using the Data Structures and other constructs provided in the JDK. Java 5 introduced a new set of concurrency related APIs in its java.util.concurrent package. As I said <a href="http://www.javabeat.net/2012/06/simple-introduction-to-fork-join-framework-in-java-7/" title="Simple introduction to Fork-Join Framework in Java 7" target="_blank">here</a>, not many of the developers are aware of these APIs and very few of the make use of it in their code. </p>
<p>There were quite a few new Collection classes which got introduced in Java 5 and one of them is the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" title="BlockingQueue in Java" target="_blank">BlockingQueue</a>.</p>
<h4>BlockingQueue in Java</h4>
<p>The JavaDoc says:<br />
<a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" target="_blank">BlockingQueue</a> is &#8220;A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.&#8221; There are multiple methods which are supported to retrieve and add elements to the queue wherein one pair throws an exceptions, one of them waits for some fixed time and one pair which blocks until the queue is full/empty. The methods which blocks the thread are the <strong>put(e)</strong> and <strong>take</strong>. </p>
<p>In a typical producer-consumer problem we would want the consumer thread to be blocked until there is something in the queue to be consumed and the producer thread to be blocked until there is some free space in the queue to add some element. With the use of normal collection classes it because quite a bit of work in implementing inter thread communication by waiting and notifying other threads about the status of the queue. The put(e) and take() methods of the BlockingQueue class are the ones which make it very easy to solve producer-consumer like problems.  </p>
<p>Lets take a scenario where the producer thread would watch for the files being modified in some directory and add those files to the queue and the consumer thread would print the contents of those files on to the console. </p>
<h4>Producer thread</h4>
<p>If you are not familiar with implementing the WatchService in Java, you must first read <a href="http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/" title="Implementing WatchService API in Java 7 to monitor the directory changes" target="_blank">this</a> to get an idea of how it works. </p>
<pre class="brush: java; title: ; notranslate">
class FileProducer implements Runnable{

  BlockingQueue&lt;Path&gt; filesList;
  Path rootPath;

  public FileProducer(BlockingQueue&lt;Path&gt; filesList, 
                      Path rootPath){
    this.filesList = filesList;
    this.rootPath = rootPath;
  }

  @Override
  public void run() {
    try {
      WatchService service = 
          FileSystems.getDefault().newWatchService();

      rootPath.register(service,
              StandardWatchEventKinds.ENTRY_MODIFY);

      while(true){
        WatchKey key = service.take();

        for (WatchEvent event : key.pollEvents()){

          Path relativePath = (Path)event.context();

          Path absolutePath =
                    Paths.get(rootPath.toString(),
                            relativePath.toString());

          filesList.put(absolutePath);

        }

        //reset is invoked to put the key back to ready
        boolean valid = key.reset();

        //If the key is invalid, just exit.
        if ( !valid){
          break;
        }
      }

    } catch (IOException e) {

      e.printStackTrace();

    } catch (InterruptedException e) {

      e.printStackTrace();

      Thread.currentThread().interrupt();
    }

  }
}
</pre>
<p>The producer thread above watches a certain directory for file modifications and adds the absolute path of the file into the BlockingQueue collection passed to the producer thread via its constructor. </p>
<h4>Consumer Thread</h4>
<p>The consumer thread would invoke take() on the BlockingQueue instance and then use the <a href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/" title="A peek into the Files utility which is part of java.nio package in Java 7" target="_blank">Files</a> API to read the contents. As take() is a blocking call, if the filesList collection is empty then it would just block and wait for the data to be available in the filesList collection. </p>
<pre class="brush: java; title: ; notranslate">
class FileConsumer implements Runnable{

  BlockingQueue&lt;Path&gt; filesList;
  Path rootPath;

  public FileConsumer(BlockingQueue&lt;Path&gt; filesList, 
                      Path rootPath){
    this.filesList = filesList;
    this.rootPath = rootPath;
  }

  @Override
  public void run(){
    try {
      while(true){

        Path fileToRead = filesList.take();

        List&lt;String&gt; linesInFile = 
            Files.readAllLines(fileToRead, 
                               Charset.defaultCharset());

        System.out.println(&quot;reading file: &quot;+fileToRead);

        for ( String line : linesInFile){
          System.out.println(line);
        }

      }
    } catch (InterruptedException e) {

      e.printStackTrace();

      Thread.currentThread().interrupt();
    } catch (IOException e) {

      e.printStackTrace();

    }

  }
}
</pre>
<p>Note: If you are writing to a file using Vim or some other editors which creates temporary files then you have to make sure you exclude such files being added to the queue. </p>
<h4>Invoking the Producer and consumer</h4>
<pre class="brush: java; title: ; notranslate">
public class ProducerConsumerSample {

  public static void main(String[] args) {
 
    BlockingQueue&lt;Path&gt; filesList = 
        new LinkedBlockingQueue&lt;&gt;(10);
 
    Path rootPath = Paths.get(&quot;/tmp/nio&quot;);
    
    Thread producerThread = 
        new Thread(new FileProducer(filesList, rootPath));
    Thread consumerThread = 
        new Thread(new FileConsumer(filesList, rootPath));
 
    producerThread.start();
    consumerThread.start();
  }

}
</pre>
<p>Pretty straight forward- create instances of both the threads and then launch them. You can create multiple consumer threads as well! In the above example we make use of the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html" title="LinkedBlockingQueue" target="_blank">LinkedBlockingQueue</a> which is one of the implementations of the BlockingQueue. </p>
<p>You have to make sure you import corresponding classes in your source code. You can have all the three classes defined in the same file and name the file as ProducerConsumerSample.java and compile and run the code. Once you have the code running, then go to your terminal and type:</p>
<pre class="brush: bash; title: ; notranslate">
/tmp/nio$ touch file1
/tmp/nio$ echo &quot;this is file1&quot; &gt;&gt; file1
/tmp/nio$ touch file2
/tmp/nio$ echo &quot;this is file2&quot; &gt;&gt; file2
</pre>
<p>and the output you see on the terminal of your java program is:</p>
<pre class="brush: bash; title: ; notranslate">
reading file: /tmp/nio/file1
reading file: /tmp/nio/file1
this is file1
reading file: /tmp/nio/file2
reading file: /tmp/nio/file2
this is file2
</pre>
<p>Note: This code was compiled and tested on a Linux platform, please find similar ways of creating files on Windows when you run your code. </p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Fjava-5-0%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/java-5-0/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/java-5-0/feed/" data-count="vertical" data-text="Java 5.0" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Java Agents</title>
		<link>http://www.javabeat.net/2012/06/introduction-to-java-agents/</link>
		<comments>http://www.javabeat.net/2012/06/introduction-to-java-agents/#comments</comments>
		<pubDate>Sat, 16 Jun 2012 04:12:38 +0000</pubDate>
		<dc:creator>sraja</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[Java Agents]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4168</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this article we will discuss about Java Agents. Java Agents are software components that provide instrumentation capabilities to an application. In the context of agents, instrumentation provides the capability of re-defining the content of class that is loaded at run-time. We will discuss this in more detail in the further sections. Download Source Code: [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this article we will discuss about <strong><em>Java Agents</em></strong>. <strong>Java Agents</strong> are software components that provide instrumentation capabilities to an application. In the context of agents, <strong><em>instrumentation</em></strong> provides the capability of re-defining the content of class that is loaded at run-time. We will discuss this in more detail in the further sections.</p>
<blockquote><p><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/JavaAgent-Introduction.zip" title=" downloaded 399 times" >Java Agents (399)</a></p></blockquote>
<h2>Writing the first agent</h2>
<p>This section details on writing the first<strong> java agent</strong>. The purpose of the agent will be get as simple as possible as the aim of this section is just to get a bit introduced to the the usage of <strong>java agents</strong>. Coding a agent requires writing a java class that has the <em>premain()</em> method. Please refer the below code.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.test;
import java.lang.instrument.Instrumentation;
public class TestJavaAgent {
	public static void premain(String agentArgument,
                   Instrumentation instrumentation){
		System.out.println(&amp;quot;Test Java Agent&amp;quot;);
	}
}
</pre>
<p>Note that it is mandatory for agents to have the above method with the exact signature. Note that the above agent does nothing another that printing sample content to the console.</p>
<pre class="brush: java; title: ; notranslate">
Manifest-Version: 1.0
Premain-Class: net.javabeat.articles.javaagent.
                                test.TestJavaAgent
</pre>
<p>Agents are packaged as jar files and are made visible to the application using the option &#8216;javaagent&#8217;. Note that it is essential for the jar file to have the Premain-Class attribute that specifies the fully qualified name of the agent class containing the premain method. Now that we have written an agent, we have to make use of the agent. For making use of the agent, let us create a sample java class as follows. Note that nowhere in the code, we are invoking the agent. Instead while running the application, agents are specified as virtual machine arguments.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.test;

public class TestMain {

	public static void main(String[] args) {
		System.out.println(&amp;quot;Test Main Class&amp;quot;);
	}
}
</pre>
<ul>
<li>Create a jar file called &#8216;test-agent.jar&#8217; by packaging the class file &#8216;net.javabeat.articles.javaagent.test.TestJavaAgent&#8217; and the manifest file &#8216;MANIFEST.MF&#8217;</li>
<li>Make use of the command, to run the agent, java -javaagent:test-agent.jar net.javabeat.articles.javaagent.test.TestMain</li>
</ul>
<p>The above command will produce the below output,</p>
<pre class="brush: java; title: ; notranslate">
Test Java Agent
Test Main Class
</pre>
<p>Note that there are several things to be noted in the above section. First of all, the agent to be run is passed as virtual machine parameter to the application. This is done through the option &#8216;javaagent&#8217;, what follows after that is &#8216;:&#8217; followed by the path to the jar file. Note that agent classes are invoked first before the above application classes, this can be seen from the output produced by the sample program.</p>
<h2>Writing a simple Agent</h2>
<p>Now that we have familiarized with the several aspects involved in writing a simple agent, let us start adding some more functionality to the agent in this section. Consider the below code snippet representing the agent,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.simple;
import java.lang.instrument.Instrumentation;
public class SimpleAgent {
	public static void premain(String agentArguments,
                      Instrumentation instrumentation){
		System.out.println(&amp;quot;Simple Agent&amp;quot;);
		SimpleClassTransformer transformer =
                    new SimpleClassTransformer();
		instrumentation.addTransformer(transformer);
	}
}
</pre>
<p>Note that the very purpose of having agent is to provide instrumentation capabilities to the application – i.e. the capability to re-define the signature of the class files during run-time. The method premain() is passed with Instrumentation object that serves its very purpose. Using Instrumentation object it is possible to adding transformer objects. Transformer object does the real job of transforming (or re-defining) the content of class files at run-time. The above code defines a transformer object, whose declaration is given below,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.simple;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
public class SimpleClassTransformer implements ClassFileTransformer{
	public byte[] transform(ClassLoader    loader,
            String              className,
            Class            classBeingRedefined,
            ProtectionDomain    protectionDomain,
            byte[]              classfileBuffer)
			throws IllegalClassFormatException {

		System.out.println(className);
		return classfileBuffer;
	}
}
</pre>
<p>Note that, a transformer object must implement the ClassFileTransformer interface and the abstract method transform needs to be overridden. This method will be called for every class that is loaded as part of the application. Note that the content of the class can be represented as byte array and this method can re-define the class content that returnss a different byte array (as denoted by the method signature). For simplicity, this method returns the original class byte array that is passed to it.</p>
<pre class="brush: java; title: ; notranslate">
Manifest-Version: 1.0
Premain-Class: net.javabeat.articles.javaagent.simple.SimpleAgent
</pre>
<p>Given above is the content of the manifest file for the agent. Note that for testing the agent, we need a sample application file which is given below. To illustrate the behavior of class loading, the application creates instances for Test classes.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.simple;
public class SimpleMain {
	public static void main(String[] args) {
		Test1 one = new Test1();
		Test2 two = new Test2();
		System.out.println(&amp;quot;Simple Main &amp;quot; + one + two);
	}
}
class Test1{}
class Test2{}
</pre>
<p>Running the above application along with the agent will produce the following output.</p>
<pre class="brush: java; title: ; notranslate">
Simple Agent
net/javabeat/articles/javaagent/simple/SimpleMain
net/javabeat/articles/javaagent/simple/Test1
net/javabeat/articles/javaagent/simple/Test2
Simple Main net.javabeat.articles.javaagent.simple.
Test1@61de33net.javabeat.articles.javaagent.simple.Test2@14318bb
</pre>
<h2>Agents for collecting statistical data</h2>
<p>In the last section, we have seen how to make use of Instrumentation object. We also saw how to manipulate Instrumentation object by adding Transformer objects. In this final section, we will see the real capability of agents for providing some statistical information about the methods being loaded for a particular class. For the purpose of illustration, let us expand the scope of the sample by provide a business class having empty business methods. Let us also assume that because the methods are for external usage, all the methods have to be public.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.statistics;
public class MyBusinessClass {
	public void bizMethod1(){
		System.out.println(&amp;quot;Biz Method 1&amp;quot;);
	}
	@SuppressWarnings(&amp;quot;unused&amp;quot;)
	private void bizMethod2(){
		System.out.println(&amp;quot;Biz Method 2&amp;quot;);
	}
}
</pre>
<p>The above code has the definition of the business class. Deliberately, the modifier for the method bizMethod2() is given as private. The agent class is given below. Note that, as illustrated in the last section, this class makes use of Instrumentation object to add transformer objects to it.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.statistics;
import java.lang.instrument.Instrumentation;
public class StatisticsAgent {
	public static void premain(String agentArguments,
                         Instrumentation instrumentation){
		StatisticsClassTransformer transformer =
                   new StatisticsClassTransformer();
		instrumentation.addTransformer(transformer);
	}
}
</pre>
<p>The flavor of the Transformer class that has the functionality of providing statistical information is given below. At this point, note that by the time when the agent is invoked, the class is not loaded. It is only during the class loading time, the agent is invoked. Hence reflection related APIs cannot be used at this point. For querying the method information for a particular class, the implementation makes use of ASM (byte code analysis library).</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.statistics;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.List;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;

public class StatisticsClassTransformer implements ClassFileTransformer{

	public byte[] transform(ClassLoader    loader,
            String              className,
            Class            classBeingRedefined,
            ProtectionDomain    protectionDomain,
            byte[]              classfileBuffer)
			throws IllegalClassFormatException {

		System.out.println();
		System.out.println(&amp;quot;Processing class &amp;quot; + className);

		String normalizedClassName = className.replaceAll(&amp;quot;/&amp;quot;, &amp;quot;.&amp;quot;);

		ClassReader classReader = null;
		try {
			classReader = new ClassReader(normalizedClassName);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		ClassNode classNode = new ClassNode();
		classReader.accept(classNode, ClassReader.SKIP_DEBUG);

		@SuppressWarnings(&amp;quot;unchecked&amp;quot;)
		List allMethods = classNode.methods;
		for (MethodNode methodNode : allMethods){
			System.out.println(methodNode.name);
		}
		return classfileBuffer;
	}

	private static void processBizMethods(Class classObject) {
		if (MyBusinessClass.class.equals(classObject)){
			Method[] allMethods = classObject.getDeclaredMethods();
			for (Method aMethod : allMethods){
				System.out.println(aMethod.getName());
				int modifiers = aMethod.getModifiers();
				if (Modifier.isPrivate(modifiers)){
					System.out.println(&amp;quot;Method &amp;quot; +
                                        aMethod.getName() + &amp;quot; is private&amp;quot;);
				}
			}
		}
	}

	public static void main(String[] args) {
		processBizMethods(MyBusinessClass.class);
	}
}
</pre>
<p>The content of the manifest file for the above agent is given below.</p>
<pre class="brush: java; title: ; notranslate">
Manifest-Version: 1.0
Premain-Class: net.javabeat.articles.javaagent.statistics.StatisticsAgent
</pre>
<p>The content of the application that triggers the agent class is given below.</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.articles.javaagent.statistics;
public class StatisticsMain {
	public static void main(String[] args) {
		MyBusinessClass object = new MyBusinessClass();
		System.out.println(&amp;quot;Biz Object &amp;quot; + object);
	}
}
</pre>
<p>The output of the application is given below,</p>
<pre class="brush: java; title: ; notranslate">
Processing class net/javabeat/articles/javaagent/statistics/StatisticsMain
&amp;lt;init&amp;gt;
main

Processing class net/javabeat/articles/javaagent/statistics/MyBusinessClass
&amp;lt;init&amp;gt;
bizMethod1
bizMethod2
Biz Object net.javabeat.articles.javaagent.statistics.MyBusinessClass@a59698
</pre>
<h2>Conclusion</h2>
<blockquote><p><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/JavaAgent-Introduction.zip" title=" downloaded 399 times" >Java Agents (399)</a></p></blockquote>
<p>This article provides introductory concepts about <strong>Java agents</strong> which are introduced from 5.0. It provides a good starter about the usage of agents by providing lot of examples. Hope the readers will be benefited after reading this article.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/introduction-to-java-agents/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Apache POI &#8211; Reading Excel sheet using Java</title>
		<link>http://www.javabeat.net/2007/10/apache-poi-reading-excel-sheet-using-java/</link>
		<comments>http://www.javabeat.net/2007/10/apache-poi-reading-excel-sheet-using-java/#comments</comments>
		<pubDate>Tue, 16 Oct 2007 11:41:42 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[Apache POI]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=113</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>POI, Apache POI &#8211; Java API to access Microsoft format files. POI (Poor Obfuscation Implementation) API is a fantastic way for Java programmers to access Microsoft document formats. The POI project consists of APIs for manipulating various file formats based upon Microsoft&#8217;s OLE 2 Compound Document format using pure Java. In short, you can read [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong style="font-size: 13px;"><em>POI</em></strong><span style="font-size: 13px;">, Apache POI &#8211; Java API to access Microsoft format files. POI (Poor Obfuscation Implementation) API is a fantastic way for Java programmers to access Microsoft document formats. The POI project consists of APIs for manipulating various file formats based upon Microsoft&#8217;s OLE 2 Compound Document format using pure Java. In short, you can read and write MS Excel files using Java. An alternate way of generating a spreadsheet is via the Cocoon serializer.</span></p>
<p>HSSF is the POI Project&#8217;s pure Java implementation of the Excel &#8217;97(-2002) file format. We will see how to read the data from a Excel sheet and display in console using java code in this article.</p>
<h2>Features of HSSF</h2>
<ul>
<li>HSSF provides a way to read spreadsheets create, modify, read and write XLS.</li>
<li>Eventmodel api for efficient read-only access.</li>
<li>It provides full usermodel api for creating, reading and modifying XLS files.</li>
</ul>
<h2>Where to get the POI API?</h2>
<p>You can download the POI API from <a href="http://poi.apache.org/" target="_blank">http://poi.apache.org/</a></p>
<h2>Apache POI &#8211; Terminology</h2>
<p>Before getting in to HSSF, we will see some of the POI-Terminologys</p>
<ul>
<li>POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats.</li>
<li>HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel.</li>
<li>HDF (Horrible Document Format): Java API to read and write Microsoft Word 97.</li>
<li>HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java.</li>
</ul>
<h2>Reading data from Excel format file and displaying to console</h2>
<p>Let us assume we have the following excel file (test.xls) with us.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2007/10/11.jpg"><img class="aligncenter size-medium wp-image-893" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2007/10/11-300x191.jpg" width="300" height="191" /></a>Now let us see how to read through the rows and cells and get the data and display in the console.</p>
<h2>Apache POI &#8211; Code Sample</h2>
<p>The following java program reads a excel file and displays the data to the console.</p>
<pre class="brush: java; title: ; notranslate">
/*
* POIExcelReader.java
*
* Created on 7 October, 2007, 9:05 PM
*/

package com.ms.util;

//~--- non-JDK imports --------------------------------------------------------

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

//~--- JDK imports ------------------------------------------------------------

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import java.util.Iterator;

/**
* This java program is used to read the data from a Excel file and display them
* on the console output.
*
* @author dhanago
*/
public class POIExcelReader
{

/** Creates a new instance of POIExcelReader */
public POIExcelReader ()
{}

/**
* This method is used to display the Excel content to command line.
*
* @param xlsPath
*/
@SuppressWarnings (&quot;unchecked&quot;)
public void displayFromExcel (String xlsPath)
{
InputStream inputStream = null;

try
{
inputStream = new FileInputStream (xlsPath);
}
catch (FileNotFoundException e)
{
System.out.println (&quot;File not found in the specified path.&quot;);
e.printStackTrace ();
}

POIFSFileSystem fileSystem = null;

try
{
fileSystem = new POIFSFileSystem (inputStream);

HSSFWorkbook      workBook = new HSSFWorkbook (fileSystem);
HSSFSheet         sheet    = workBook.getSheetAt (0);
Iterator rows     = sheet.rowIterator ();

while (rows.hasNext ())
{
HSSFRow row = rows.next ();

// display row number in the console.
System.out.println (&quot;Row No.: &quot; + row.getRowNum ());

// once get a row its time to iterate through cells.
Iterator cells = row.cellIterator ();

while (cells.hasNext ())
{
HSSFCell cell = cells.next ();

System.out.println (&quot;Cell No.: &quot; + cell.getCellNum ());

/*
 * Now we will get the cell type and display the values
 * accordingly.
 */
switch (cell.getCellType ())
{
	case HSSFCell.CELL_TYPE_NUMERIC :
	{

		// cell type numeric.
		System.out.println (&quot;Numeric value: &quot; + cell.getNumericCellValue ());

		break;
	}

	case HSSFCell.CELL_TYPE_STRING :
	{

		// cell type string.
		HSSFRichTextString richTextString = cell.getRichStringCellValue ();

		System.out.println (&quot;String value: &quot; + richTextString.getString ());

		break;
	}

	default :
	{

		// types other than String and Numeric.
		System.out.println (&quot;Type not supported.&quot;);

		break;
	}
}
}
}
}
catch (IOException e)
{
e.printStackTrace ();
}
}

/**
* The main executable method to test displayFromExcel method.
*
* @param args
*/
public static void main (String[] args)
{
POIExcelReader poiExample = new POIExcelReader ();
String         xlsPath    = &quot;c://test//test.xls&quot;;

poiExample.displayFromExcel (xlsPath);
}
}</pre>
<h3>Code walk through</h3>
<ul>
<li><strong>POIFSFileSystem</strong> is the main class for <strong>POIFS</strong> system. POIFSFileSystem manages the entire life cycle for the file system.</li>
<li>POIFSFileSystem has a constructor which can take a InputStream as the parameter. Here in the above code we have created a FileInputStream and assigned to the InputStream. This inputStream object is passed to the POIFSFileSystem constructor and POIFSFileSystem object is created.</li>
<li>After creating POIFSFileSystem object, <strong>HSSFWorkbook</strong> object has to be created.</li>
<li><strong>HSSFWorkbook</strong> object is a high level representation of a workbook. This is the first object most users will construct whether they are reading or writing a workbook. It is also the top level object for creating new sheets/etc.</li>
<li>HSSFWorkbook object is created using POIFSFileSystem object. By using the constructor HSSFWorkbook(POIFSFileSystem fs).</li>
<li>Once we get the HSSFWorkbook object it is very easy to get the Sheet. HSSFWorkbook has a method getSheetAt(int index) Get the HSSFSheet object at the given index.</li>
<li>Note that index starts at zero. In our code we have used like &#8220;workBook.getSheetAt (0)&#8221; means we are intrested in first sheet.</li>
<li>The above method will give us a HSSFSheet object.</li>
<li><strong>HSSFSheet</strong> object has got a method called &#8220;rowIterator()&#8221;. This will give us all the rows in a Iterator and is of type HSSFRow</li>
<li>By Iterating this in a while loop we can get each and every for and cells in them.</li>
<li><strong>HSSFRow</strong> has a method called &#8220;cellIterator()&#8221; This will also return a Iterator consisting of type <strong>HSSFCell</strong>.</li>
<li>By Iterating this we will get individual HSSFCell objects.</li>
<li>By getting the HSSFCell we can get the cell type by using the method &#8220;getCellType()&#8221;</li>
<li>By finding the cell type we can use the appropriate method to get the values as shown in the code above. Then it is up to the programmers requirement to use the values got accordingly. Here we have simply displayed it in the console.</li>
</ul>
<h3>Output</h3>
<pre class="brush: java; title: ; notranslate">
Row No.: 0
Cell No.: 0
String value: Name
Cell No.: 1
String value: Age
Cell No.: 2
String value: URL
Row No.: 1
Cell No.: 0
String value: Muthukumar Dhanagopal
Cell No.: 1
Numeric value: 33.0
Cell No.: 2
String value: http://javawave.blogspot.com
Row No.: 2
Cell No.: 0
String value: Krish
Cell No.: 1
Numeric value: 27.0
Cell No.: 2
String value: http://javabeat.net
Row No.: 3
Cell No.: 0
String value: Sri Hariharan Muthukumar
Cell No.: 1
Numeric value: 3.0
Cell No.: 2
String value: http://dhanago.blogspot.com
</pre>
<h2>Other operations you can do with HSSF</h2>
<ul>
<li>to create a new workbook</li>
<li>to create a sheet</li>
<li>to create cells</li>
<li>to create date cells</li>
<li>Working with different types of cells</li>
<li>Aligning cells</li>
<li>Working with borders</li>
<li>Fills and color</li>
<li>Merging cells</li>
<li>Working with fonts</li>
<li>Custom colors</li>
<li>Reading and writing</li>
<li>Use newlines in cells.</li>
<li>Create user defined data formats</li>
<li>Fit Sheet to One Page</li>
<li>Set print area for a sheet</li>
<li>Set page numbers on the footer of a sheet</li>
<li>Shift rows</li>
<li>Set a sheet as selected</li>
<li>Set the zoom magnification for a sheet</li>
<li>Create split and freeze panes</li>
<li>Repeating rows and columns</li>
<li>Headers and Footers</li>
<li>Drawing Shapes</li>
<li>Styling Shapes</li>
<li>Shapes and Graphics2d</li>
<li>Outlining</li>
<li>Images</li>
<li>Named Ranges and Named Cells</li>
<li>How to set cell comments</li>
<li>How to adjust column width to fit the contents</li>
</ul>
<h2>References</h2>
<ul>
<li><a href="http://poi.apache.org/hssf/index.html" target="_blank">http://poi.apache.org/hssf/index.html</a></li>
</ul>
<h2>Summary</h2>
<p>Through this article i have just given the much needed push (Even eagles need a push). It is up to the programmers or developers who wanna proceed further to know more about POI and its API. Now a days there are many applications which are there in real time which uses Excel sheets and need to be read from Java and vice verse. POI is a very helpful, fantastic and easy tool helping Java programmers in achieving this.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/10/apache-poi-reading-excel-sheet-using-java/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Regular Expressions in Java</title>
		<link>http://www.javabeat.net/2007/10/regular-expressions-in-java/</link>
		<comments>http://www.javabeat.net/2007/10/regular-expressions-in-java/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 11:35:46 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[Regular Expression]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=104</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction Regular Expressions are basically patterns of characters which are used to perform certain useful operations on the given input. The operations include finding particular text, replacing the text with some other text, or validating the given text. For example, we can use Regular Expression to check whether the user input is valid for [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2 id="Introduction">1) Introduction</h2>
<p align="justify"><em><strong>Regular Expressions</strong></em> are basically patterns of characters which are used to perform certain useful operations on the given input. The operations include <em><strong>finding particular text, replacing the text with some other text, or validating the given text</strong></em>. For example, we can use Regular Expression to check whether the user input is valid for a field like Email Id or a telephone number.</p>
<p align="justify"><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a title="New Features in Java 5.0" href="http://www.javabeat.net/2007/08/new-features-in-java-5-0/">Java 5.0 Features</a></li>
<li><a title="Permanent Link to Book Review: Pro Java 7 NIO.2" href="http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/" rel="bookmark">Book Review: Pro Java 7 NIO.2</a></li>
<li><a title="AutoBoxing in Java 5.0" href="http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/" rel="bookmark">AutoBoxing in Java 5.0</a></li>
</ul>
<h2>2) java.util.regex Package</h2>
<p align="justify">The <em><strong>java.util.regex</strong></em> package provides the necessary classes for using Regular Expressions in a java application. This package has been introduced in <em><strong>Java 1.4</strong></em>. It consists of three main classes namely,</p>
<ul>
<li><em><strong>Pattern</strong></em></li>
<li><em><strong>Matcher</strong></em></li>
<li><em><strong>PatternSyntaxException</strong></em></li>
</ul>
<h2>3) Pattern Class</h2>
<p align="justify">A regular expression which is specified as a string, should be first compiled into an instance of <code>Pattern</code> class. The resulting pattern can then be used to create an instance of <code>Matcher</code> class which contains various in-built methods that helps in performing a match against the regular expression. Many <code>Matcher</code> objects can share the same <code>Pattern</code> object.</p>
<p align="justify">Let us now discuss about the important methods in <code>Pattern</code> class.</p>
<h3>a) compile() method</h3>
<p align="justify">Before working with, we need a compiled form of regular expression pattern, by calling the <code>Pattern.compile()</code> method which returns a new<br />
<code>Pattern</code> object. Note that <code>compile()</code> is a static method, so we dont an instance of the <code>Pattern</code> class.</p>
<p align="justify">There are two forms of <code>compile()</code> method,</p>
<ul>
<li>compile(String regex)</li>
<li>compile(String regex, int flags)</li>
</ul>
<p align="justify">In the first form of <code>compile()</code> method, we pass the regular expression that would be compiled. In the second form of this method, we have an additional parameter which is used to specify the match flags that has to be applied. The flags can be either <code>CASE_INSENSITIVE</code>, <code>MULTILINE</code>, <code>DOTALL</code>, <code>UNICODE_CASE</code> or <code>CANON_EQ</code> based on which matching would be done.</p>
<h3>b) matcher() method</h3>
<p align="justify">The <code>matcher()</code> method is used to create new <code>Matcher</code> object for an input for a given pattern, which can be used to perform matching operations. The syntax is as follows,</p>
<p align="justify">matcher(String input)</p>
<h3>c) matches() method</h3>
<p align="justify"><!--?php include("http://www.javabeat.net/articles/templates/article_banner_middle.php"); ?--><br />
The <code>Pattern</code> class provides a <code>matches()</code> method, which is a static method. This method returns true only if the entire input text matches the pattern. This method internally depends on the <code>compile()</code> and <code>matcher()</code> methods of the <code>Pattern</code> object. The syntax for this static matches() method is,</p>
<p align="justify">Pattern.matches(pattern, inputSequence);</p>
<p align="justify">Let us see a simple example,</p>
<p><strong>RegExpTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpTest {
    public static void main(String[] args) {

        String inputStr = &quot;Computer&quot;;
        String pattern = &quot;Computer&quot;;
        boolean patternMatched = Pattern.matches(pattern, inputStr);
        System.out.println(patternMatched);

    }
}</pre>
<p align="justify">The <code>matches()</code> method returns true in this case and hence we get the output as true. If in case, we had given the input string as <code>"ComputerScience"</code>, then the <code>matches()</code> method would have returned false.</p>
<p align="justify">In the static <code>matches()</code> method, when we specify an input string and a pattern to the <code>Pattern.matches()</code> method, the pattern gets compiled into a <code>Pattern</code> object which is used for matching operation. This is inefficient because every time we specify an input string and pattern, compilation of the pattern is done. Hence, its better to use the non static <code>matches()</code> method in <code>Matcher</code> class. (This <code>matches()</code> method would be discussed when dealing with Matcher class in the forth-coming section).</p>
<h3>d) pattern() method</h3>
<p align="justify">Returns the regular expression as a string from which this pattern was compiled.</p>
<h3>e) split() method</h3>
<p align="justify">This method is used to split the given input text based on the given pattern. It returns a String array.</p>
<p align="justify">There are two forms of <code>split()</code> method,</p>
<ul>
<li>split(String input)</li>
<li>split(String input, int limit)</li>
</ul>
<p align="justify">In the second form, we have an argument called <code>limit</code> which is used to specify the limit i.e the number of resultant strings that have to be obtained by <code>split()</code> method.</p>
<p align="justify">Let us see a simple example for the <code>split()</code> method,</p>
<pre class="brush: java; title: ; notranslate">Pattern pattern = Pattern.compile(&quot;ing&quot;);
Matcher matcher = pattern.matcher(&quot;playingrowinglaughingsleepingweeping&quot;);
String[] str = pattern.split(input, 4);
for(String st : str)
{
    System.out.println(st);
}</pre>
<p align="justify">In the above code, we had specified the limit of number of Strings to be returned as 4. Hence we would get 4 strings as the result.</p>
<p align="justify">The output for the above code is,<br />
play<br />
row<br />
laugh<br />
sleepingweeping</p>
<h3>f) flag() method</h3>
<p align="justify">This method returns this pattern&#8217;s match flags which would have been specified when the pattern was compiled.</p>
<h2 id="Matcher Class">4) Matcher Class</h2>
<p align="justify">The <code>Matcher</code> class which contains various in-built methods such as <code>matches()</code>, <code>find()</code>, <code>group()</code>, <code>replaceFirst()</code>, <code>replaceAll()</code> etc., that help us to check whether the desired pattern occurs in the given text or search the desired pattern in the text or to replace the occurrence of the pattern in the text with some other set of characters as per the requirement.</p>
<p align="justify">Let us now discuss about the important methods in <code>Matcher</code> class.</p>
<h3>a) matches() method</h3>
<p align="justify">The <code>matches()</code> method available in the <code>Matcher</code> class is used to match an input text against a pattern. This method returns true only if the entire input text sequence matches the pattern. Consider the following example,</p>
<pre class="brush: java; title: ; notranslate">String input = &quot;Java1.4, Java1.5, Java1.6&quot;;
Pattern pattern = Pattern.compile(&quot;Java&quot;);
Matcher matcher = pattern.matcher(input);
boolean patternMatched = matcher.matches();</pre>
<p align="justify">In this case the value of <code>patternMatched</code> will be false since the entire input string <code>"Java1.4, Java1.5, Java1.6"</code> does not match the regular expression pattern <code>"Java"</code> and hence <code>matches()</code> method returns false. Let us use the same <code>Pattern</code> object in another <code>Matcher</code> object and see how it works. Consider the following code,</p>
<pre class="brush: java; title: ; notranslate">String input = &quot;Java&quot;;
Matcher matcher1 = pattern.matcher(input);
boolean patternMatched1 = matcher1.matches();</pre>
<p align="justify">Here, the <code>matches()</code> method returns true since the entire input sequence matches the pattern <code>"Java"</code>. The <code>matches()</code> method finds appropriate use in searching for particular whole words in a given text.</p>
<p align="justify">Let us see another example to know about some other methods available in <code>Matcher</code> class,</p>
<pre class="brush: java; title: ; notranslate">String input = &quot;Java1.4, Java1.5, Java1.6&quot;;

Pattern pattern = Pattern.compile(&quot;Java&quot;);
Matcher matcher = pattern.matcher(input);

while (matcher.find()){
    System.out.println(matcher.group() + &quot;: &quot; +matcher.start() + &quot;: &quot; + matcher.end());
}</pre>
<p align="justify">The output of the above code is,</p>
<pre class="brush: java; title: ; notranslate">Java: 0: 4
Java: 9: 13
Java: 18: 22</pre>
<p align="justify"><!--?php include("http://www.javabeat.net/articles/templates/article_banner_middle.php"); ?--><br />
In the above example code, we see the usage of <code>find()</code>, <code>group()</code>, <code>start</code> and <code>end()</code> methods.</p>
<p align="justify">Now, let us know about the purpose of those methods.</p>
<h3>b) find() method</h3>
<p align="justify">The <code>find()</code> method in <code>Matcher</code> Class returns true if the pattern occurs anywhere in the input string.<br />
It has two forms,</p>
<ul>
<li>find()</li>
<li>find(int start)</li>
</ul>
<p align="justify">In our example, we used the first form of <code>find()</code> method. It searches for all occurrences of the pattern <code>"Java"</code> in the given input String <code>"Java1.4, Java1.5, Java1.6"</code> and then returns true if a subsequence in the input matches the desired pattern.</p>
<p align="justify">In the second form of <code>find()</code> method, we have an argument that is used to specify the start index of find operation.</p>
<h3>c) group() method</h3>
<p align="justify">The <code>group()</code> method in <code>Matcher</code> Class returns the piece of input that has matched the pattern.</p>
<h3>d) start() method and end() method</h3>
<p align="justify">The <code>start()</code> and <code>end()</code> methods in <code>Matcher</code> Class return the start and end indexes respectively, for each occurrence of the subsequences in the input text that has matched the defined regular expression pattern.</p>
<h2>5) PatternSyntaxException Class</h2>
<p align="justify"><code>PatternSyntaxException</code> is an unchecked exception which is thrown when there is any syntax error in a regular expression pattern. It has various methods like <code>getDescription()</code>, <code>getIndex()</code>, <code>getMessage()</code> and <code>getPattern()</code> which enable us to get the details of the error.</p>
<p align="justify">We have just seen very simple examples to understand the basics of Regular Expressions in java, and about the purpose of few often used methods. With this basic knowledge, we shall discuss in depth about Regular Expression in the following sections.</p>
<h2 id="Matching any single character">6) Matching any single character</h2>
<p align="justify">The <code>'.'</code> character is used to match any single character. If suppose we use a pattern <code>'ca.'</code> then this pattern would match string inputs like <code>'car'</code>, &#8216;cat&#8217;, <code>'cap'</code> etc.. because they start with ca and then followed by another single character. Consider an example to understand this,</p>
<pre class="brush: java; title: ; notranslate">Pattern patternObj = Pattern.compile(&quot;ca.&quot;);
Matcher matcher = patternObj.matcher(&quot;cap&quot;);
if(matcher.matches()){
    System.out.println(&quot;The given input matched the pattern&quot;);
}</pre>
<p align="justify">The output of the above code is,</p>
<p>The given input matched the pattern</p>
<h2>7) Matching Special characters</h2>
<p align="justify">Suppose we need to specify <code>'.'</code> character in our pattern to indicate that the string input should contain the <code>'.'</code> character. But, in Regular Expression <code>'.'</code> has a specific meaning. So we have to specify it to the compiler that we don&#8217;t mean the Regular expression <code>'.'</code> by escaping it with a <code>'\'</code> (backslash character) which is a metacharacter. Consider the following example,</p>
<pre class="brush: java; title: ; notranslate">Pattern patternObj = Pattern.compile(&quot;.est\\.java&quot;);
Matcher matcher1 = patternObj.matcher(&quot;test.java&quot;);
Matcher matcher2 = patternObj.matcher(&quot;nest.java&quot;);

if(matcher1.matches() &amp;amp;&amp;amp; matcher2.matches()){
    System.out.println(&quot;Both the inputs matched the pattern&quot;);
}</pre>
<p align="justify">The output of this code is,</p>
<pre class="brush: java; title: ; notranslate">Both the inputs matched the pattern</pre>
<p align="justify">Hence, the use of <code>'.'</code> means to match any character, and the use of &#8216;\.&#8217; means the normal <code>'.'</code> character. We can use this backslash character wherever we need to specify a special character for some other purpose.<br />
(Note : In Java, the compiler expects a backslash character <code>'\'</code> to be always prefixed with another backslash character <code>'\'</code> when used within a String literal.)</p>
<h2>8) Matching particular characters</h2>
<p>In a given text, we may need to match specific desired characters. We have already seen that the <code>'.'</code> character will match any single character but now our requirement is to match only <code>'c'</code> or <code>'s'</code> along with other desired set of characters. In such situations, we can enclose the desired characters in parenthesis <code>[]</code> which is a metacharacter used to indicate a character set from which any one character should be available in the given text. Consider the following piece of code that illustrates the same,</p>
<pre class="brush: java; title: ; notranslate">Pattern patternObj = Pattern.compile(&quot;[CcSs]at&quot;);
Matcher matcher = patternObj.matcher(&quot;Sat&quot;);
if(matcher.matches()){
    System.out.println(&quot;The given input matched the pattern&quot;);
}</pre>
<p align="justify">The output of this code is,</p>
<pre class="brush: java; title: ; notranslate">The given input matched the pattern</pre>
<p align="justify">In the above example, we have used the pattern <code>'[CcSs]at'</code> wherein <code>Cc</code> is used to match <code>C</code> and <code>c</code>, and <code>Ss</code> matches <code>S</code> and <code>s</code>. Hence this would match inputs such as <code>Cat</code>, <code>cat</code>, <code>Sat</code> and <code>sat</code>.</p>
<h2>9) Matching range of characters</h2>
<p align="justify">In Regular expressions, we use the metacharacter <code>'-'</code> i.e a hyphen symbol to specify a range of characters. For example, we can specify the range of lowercase alphabets as <code>'[a-z]'</code> and <code>'[A-Z]'</code> in case of uppercase alphabets.</p>
<p align="justify">Consider a situation where we need the input to start with a number from <code>0</code> to <code>3</code>, then followed by any alphabet from <code>a</code> to <code>z</code> and then followed by another number that might range from <code>7</code> to <code>9</code>. The following code can be used to validate the input against such a pattern,</p>
<pre class="brush: java; title: ; notranslate">Pattern patternObj = Pattern.compile(&quot;[0-3][a-z][7-9]&quot;);
Matcher matcher = patternObj.matcher(&quot;2a8&quot;);
if(matcher.matches()){
    System.out.println(&quot;The given input matched the pattern &quot;);
}</pre>
<h2>10) Matching characters apart from a specific list</h2>
<p align="justify">We can use the <code>'^'</code> metacharacter to specify one or more characters that we want don&#8217;t expect to match. Let us achieve the same requirement in our previous example by using a different pattern that makes use of the metacharacter <code>'^'</code> ,</p>
<pre class="brush: java; title: ; notranslate">Pattern patternObj = Pattern.compile(&quot;[^3-9][a-z][7-9]&quot;);</pre>
<p align="justify">The use of <code>'^'</code> character inside <code>[]</code> indicates that those characters specified in it are not expected in the input.</p>
<p align="justify">This pattern will match the input <code>"2a8"</code> as in our previous example.</p>
<h2 id="Use of other Metacharacters in Regular Expression">11) Use of other Metacharacters in Regular Expression</h2>
<p align="justify">We have already discussed about the use of <code>'.'</code> and <code>'^'</code> metacharacters. Let us see the purpose of other metacharacters.</p>
<h3>\d</h3>
<p align="justify">This matches a numeric digit. It is the same as using the character set <code>[0-9]</code>.</p>
<h3>\D</h3>
<p align="justify">This matches any character which is non-numeric. It is the same as the use of <code>[^0-9]</code>.</p>
<h3>\s</h3>
<p align="justify">This matches a single whitespace character.</p>
<h3>\S</h3>
<p>This matches any character which is not a whitespace character.</p>
<h3>\w</h3>
<p align="justify">This matches a word character. It is equivalent to the character class <code>[A-Za-z0-9_]</code>.</p>
<h3>\W</h3>
<p align="justify">This matches a character that is not a word character. It is equivalent to the<br />
negated character class <code>[^A-Za-z0-9_]</code>.</p>
<h3>[...]</h3>
<p align="justify">This matches a single character present in between the square paranthesis.</p>
<h3>[a-f[s-z]]</h3>
<p align="justify">This specifies the <em><strong>union</strong></em> of two sets of characters, which is the same as <code>[a-fs-z]</code>, i.e it<br />
matches any character that might be either from <code>a</code> to <code>f</code> and from <code>s</code> to <code>z</code>.</p>
<h3>[a-m[f-z]]</h3>
<p align="justify">This specifies the <em><strong>intersection</strong></em> of two sets of characters, which is the same as <code>[f-m]</code>, i.e it matches any character from <code>f</code> to <code>m</code>.</p>
<h3>[^...]</h3>
<p align="justify">This matches any single character, except those characters that are specified inside the square parentheses <code>[]</code>.</p>
<h2>12) POSIX Character Classes</h2>
<p align="justify">The <code>java.util.regex</code> package provides a set of <code>POSIX character</code> classes, which are indeed shortcuts to be used in regular expressions that make it easier for us to use instead of specifying the entire pattern.</p>
<h3>\p{Lower}</h3>
<p align="justify">It can be used to match any single lowercase alphabetic character. It is the same as using <code>[a-z]</code>.</p>
<h3>\p{Upper}</h3>
<p align="justify">It can be used to match any single uppercase alphabet character. It is the same as using <code>[A-Z]</code>.</p>
<h3>\p{Alpha}</h3>
<p align="justify">It is used to match any alphabetic character. It serves the same purpose as <code>[A-Za-z]</code>.</p>
<h3>\p{Digit}</h3>
<p align="justify"><!--?php include("http://www.javabeat.net/articles/templates/article_banner_middle.php"); ?--><br />
It is used to match any single digit. It serves the same purpose as <code>[0-9]</code>.</p>
<h3>\p{Punct}</h3>
<p align="justify">It is the same as using <code>[!"#$%&amp;'()*+,- ./:;?@[\]^_`{|}~]</code>.</p>
<h3>\p{Graph}</h3>
<p align="justify">It is the same as using <code>[\p{Alpha}\p{Punct}]</code>.</p>
<h3>\p{Print}</h3>
<p align="justify">It is the same as using [\p{Graph}].</p>
<h3>\p{ASCII]</h3>
<p align="justify">It can be used to match any of the ASCII characters. It serves the same purpose as <code>U+0000</code> through <code>U+007F</code>.</p>
<h3>\p{XDigit}</h3>
<p align="justify">It matches a single hexadecimal digit. It is the same as using <code>[0-9a-fA-F]</code>.</p>
<h3>\p{Space}</h3>
<p align="justify">It is used to match a single whitespace character. It is the same as using <code>[ \t\n\x0B\f\r]</code>.</p>
<h3>\p{Blank}</h3>
<p align="justify">It matches a single space character or a tab character.</p>
<h3>\p{Cntrl}</h3>
<p align="justify">It matches a control character. It is the same as using <code>[\x00-\x1F\x7F]</code>.</p>
<h2>13) Conclusion</h2>
<p align="justify"><strong>also read:</strong></p>
<ul>
<li><a title="New Features in Java 5.0" href="http://www.javabeat.net/2007/08/new-features-in-java-5-0/">Java 5.0 Features</a></li>
<li><a title="Permanent Link to Book Review: Pro Java 7 NIO.2" href="http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/" rel="bookmark">Book Review: Pro Java 7 NIO.2</a></li>
<li><a title="AutoBoxing in Java 5.0" href="http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/" rel="bookmark">AutoBoxing in Java 5.0</a></li>
</ul>
<p align="justify">This article is just an introduction to Regular expressions. We have seen the basics on how to use regular expressions to perform useful operations such as search, replace and validation for a given input. Regular Expressions can be effectively used to suit our application needs that involve text manipulation.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/10/regular-expressions-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generics in Java 5.0</title>
		<link>http://www.javabeat.net/2007/08/generics-in-java-5-0/</link>
		<comments>http://www.javabeat.net/2007/08/generics-in-java-5-0/#comments</comments>
		<pubDate>Tue, 14 Aug 2007 02:11:04 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[Generics]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=89</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction The feature of Generics in Java allows Applications to create classes and objects that can operate on any defined types. Programmers can now make use of the Generics feature for a much better code. There is no need for un-necessary casting when dealing with Objects in a Collection. This article provides a detailed [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p align="justify">The feature of <em><strong>Generics</strong></em> in Java allows Applications to create classes and objects that can operate on any defined types. Programmers can now make use of the Generics feature for a much better code. There is no need for <em><strong>un-necessary casting</strong></em> when dealing with Objects in a Collection. This article provides a detailed overview of Generics and its usage in different context with samples. To start with, it illustrates the need for Generics and the difficulties faced by the Developers before its origin. It will explain in detail on how to write <em><strong>Generic Classes</strong></em>, <em><strong>Generic Methods</strong></em> and so on. Then the various aspects of <em><strong>Bound Constraints</strong></em> and <em><strong>Wild-cards</strong></em> will be discussed.</p>
<ul>
<li>Buy : <a href="http://www.flipkart.com/java-generics-collections-8184042167/p/itmdyusddnjsfaxn?pid=9788184042160&amp;affid=suthukrish" target="_blank">Generics and Collections</a></li>
</ul>
<h2 id="Java Generics">2) Java Generics</h2>
<p align="justify">In this section let us explore the basis of Generics programming. As mentioned in the introductory section, Generics programming enables Classes and Methods to operate on well defined <em><strong>parametric types</strong></em> allowing clients to substitute a suitable Java type at the compile time. This prevents un-necessary casting being done in the Application code and to prevent any wrong data-type being used. To make things clear, consider the following statements.</p>
<pre class="brush: java; title: ; notranslate">Map contacts = new HashMap();
contacts.put(new Long(9912345678L), &quot;Jenny&quot;);
contacts.put(new Long(9912345679L), &quot;Johny&quot;);

Set contactValues = contacts.entrySet();
Iterator contactIterator = contactValues.iterator();

while (contactIterator.hasNext())
{
    Map.Entry anEntry = (Map.Entry)contactIterator.next(); // Line A
    Long number = (Long)anEntry.getKey(); // Line B
    String name = (String)anEntry.getValue(); // Line C
    System.out.println(number + &quot;:&quot; + name);
}</pre>
<p align="justify">The above code populates a <code>Map</code>, keyed with mobile phone for a person name. The next pieces of code try to iterate over the <code>Map</code>, thereby printing the data within it. Look at the casts down at lines A, B and C. Even though we know that we are going to add phone numbers (which is of type Long) and a person name (probably a String) into the Map, we are doing an explicit cast to get the appropriate data. The other problem we find here is, what if the client put some other data other than the <code>Long</code> data-type for the Key.</p>
<pre class="brush: java; title: ; notranslate">contacts.put(new String(&quot;9912345678L&quot;), &quot;Jenny&quot;);</pre>
<p align="justify">The above code will definitely raise an exception at the run-time. So, we find two major dis-advantages in the older code (code compiled with java 1.4 compiler or before). One is the need to have absurd cast that is being spread across the code. The other thing is that there is no procedural mechanism through which we can prevent wrong data-type being added to the above Collection.</p>
<p align="justify">The solution to the above problems is having Generics in the programming code. Let us see how the above code is re-written using Generics.</p>
<pre class="brush: java; title: ; notranslate">Map contacts = new HashMap();
contacts.put(new Long(9912345678L), &quot;Jenny&quot;);
contacts.put(new Long(9912345679L), &quot;Johny&quot;);

Set&amp;lt;Map.Entry&amp;gt; contactValues = contacts.entrySet();
Iterator&amp;lt;Map.Entry&amp;gt; contactIterator = contactValues.iterator();

while (contactIterator.hasNext())
{
    Map.Entry anEntry = contactIterator.next();
    Long number = anEntry.getKey();
    String name =  anEntry.getValue();
    System.out.println(number + &quot;:&quot; + name);
}</pre>
<p align="justify">Let us analyze what has happened in the above code. The declaration <code>Map contacts = new HashMap();</code> has now changed to <code>Map&lt;Long, String&gt; contacts = new HashMap&lt;Long, String&gt;();</code></p>
<p align="justify">The former is called a <em><strong>Raw Map</strong></em> and the latter is an example of a <em><strong>Generic Map</strong></em>. If we look at the declaration of the <code>Map</code> and the <code>HashMap</code> classes, we will find something similar to the following,</p>
<pre class="brush: java; title: ; notranslate">public interface Map { ... }</pre>
<p align="justify">The above declaration can be interpreted as : <code>Map</code> has two parametric types called <code>K</code> (meaning Key) and <code>V</code> (meaning Value). The name of the parametric types can be anything, that doesn&#8217;t matter. These changes to <code>Map</code> and all its related collection classes is there right from Java 5.0. So, whenever a clients references a <code>Map</code> interface, it cannot plainly do like the following,</p>
<pre class="brush: java; title: ; notranslate">Map mapObject = new HashMap();</pre>
<p align="justify">The compiler (Java 5.0) as soon as encountering this statement will issue a warning telling that, the declaration of <code>Map</code> is a raw-type and its references should be parameterized. Since the declaration of the <code>Map</code> interface is now parameterized with Keys and Values in the form of &lt;K, V&gt;, the client referencing the <code>Map</code> should provide a suitable type for the parametric types. Going back to our code,</p>
<pre class="brush: java; title: ; notranslate">Map contacts = new HashMap();</pre>
<p align="justify">We want the key for the <code>Map</code> to be of type <code>Long</code> and the value for the corresponding Key to be of type <code>String</code>. We also have parameterized the <code>HashMap</code> class with Long and String, since the class declaration for <code>HashMap</code> has also changed.</p>
<pre class="brush: java; title: ; notranslate">public class HashMap implements Map { … }</pre>
<p align="justify">The usage of <em><strong>parametric types</strong></em> has not only affected <code>Map</code> and <code>HashMap</code> but all the collection related classes and interfaces in the <code>java.util</code> package. In our code, contacts are made to populate in the map object by calling the <code>Map.put()</code> method. Now, the call to <code>Map.entrySet()</code> will return a <code>Set</code> containing entries which is of type <code>Map.Entry</code>. Now let us have a look over the <code>Map.entrySet()</code> method,</p>
<pre class="brush: java; title: ; notranslate">Set&amp;lt;Map.Entry&amp;gt; entrySet();</pre>
<p align="justify">The return type of <code>Map.entrySet()</code> is a <code>Set</code> which is parameterized with <code>Map.Entry</code>. <code>Map.Entry</code> is a class that will store an entry, which is nothing but a combination of Key and value. Note that <code>Map.Entry</code> is again parameterized with <code>K</code> (for Key) and <code>V</code> (for Value). In our case, the key is of type <code>Long</code> and the value is of type <code>String</code>, we have something like the following in the later part of the code,</p>
<pre class="brush: java; title: ; notranslate">Set&amp;lt;Map.Entry&amp;gt; contactValues = contacts.entrySet();</pre>
<p align="justify">The same thing applies for <code>Iterator</code> which is parameterized with <code>Map.Entry</code> which is again parameterized with <code>Long</code> and <code>String</code>. While traversing over the elements within the while loop, we have statements like the following,</p>
<pre class="brush: java; title: ; notranslate">...

Map.Entry anEntry = contactIterator.next();
Long number = anEntry.getKey();
String name =  anEntry.getValue();

...</pre>
<p align="justify">Since we well know that the <code>Iterator</code> is typed with <code>Map.Entry&lt;Long, String&gt;</code>, there is no need for an explicit type-cast. Same is the case for <code>Map.getKey()</code> and <code>Map.getValue()</code>. Since the <code>Map</code> has been parameterized with <code>Long</code> and <code>String</code>, it is not possible to add types other than the defined types. So now the following code will raise a compilation error.</p>
<pre class="brush: java; title: ; notranslate">contacts.put(new String(&quot;&quot;), new Long(1L));</pre>
<p align="justify">This ensures type-safe programming and it prevents the client code from adding any wrong data-type to the Collection.</p>
<h2 id="Writing Generic Classes">3) Writing Generic Classes</h2>
<ul>
<li><a title="New Features in Java 5.0" href="http://www.javabeat.net/2007/08/new-features-in-java-5-0/">Java 5.0 Features</a></li>
<li><a title="Permanent Link to Book Review: Pro Java 7 NIO.2" href="http://www.javabeat.net/2012/08/book-review-pro-java-7-nio-2/" rel="bookmark">Book Review: Pro Java 7 NIO.2</a></li>
</ul>
<p align="justify">Let us see how to create our own classes using Generics. Let us keep the purpose of the class as simple as holding some Object, the <em><strong>Object Holder</strong></em> class. This <em><strong>Object Holder</strong></em> class can hold any type of Java object. It provides method for getting and setting the current Object. The following shows the class declaration of the Object Holder class.</p>
<p><strong>ObjectHolder.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.classes;

public class ObjectHolder
{
    private O anyObject;

    public O getObject()
    {
        return anyObject;
    }

    public void setObject(O anyObject)
    {
        this.anyObject = anyObject;
    }

    public String toString()
    {
        return anyObject.toString();
    }
}</pre>
<p align="justify">Note the following syntax,</p>
<pre class="brush: java; title: ; notranslate">public class ObjectHolder</pre>
<p align="justify">The above statement essentially says that we wish to make the <em><strong>Object Holder</strong></em> class as a Generic Class. Technically, Object Holder is now a <em><strong>parametric class</strong></em> and <code>O</code> is called a <em><strong>type parameter</strong></em>. <code>O</code> serves as a place-holder for holding any type of Object. Note the usage of the type parameter within the class declaration. Now, the clients can use the above class by substituting any kind of object for the place-holder O. Consider the following Client program that makes use of the Object Holder class.</p>
<p><strong>ObjectHolderClient.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.classes;

import java.net.URL;

public class ObjectHolderClient
{
    public static void main(String[] args) throws Exception
    {
        ObjectHolder stringHolder =
            new ObjectHolder();
        stringHolder.setObject(new String(&quot;String&quot;));
        System.out.println(stringHolder.toString());

        ObjectHolder urlHolder = new ObjectHolder();
        urlHolder.setObject(new URL(&quot;http://www.javabeat.net&quot;));
        System.out.println(urlHolder.toString());
    }
}</pre>
<p align="justify">Note how the Clients instantiates an instance for the Object Holder class.</p>
<pre class="brush: java; title: ; notranslate">ObjectHolder stringHolder = new ObjectHolder();</pre>
<p align="justify">This is called <em><strong>type substitution</strong></em>. For the type parameter <code>O</code>, the type String is substituted. And now the calls to <code>ObjectHolder.setObject(O anyObject)</code> and <code>O ObjectHolder.getObject()</code> can be imagined <code>as ObjectHolder.setObject(String anyObject)</code> and <code>String ObjectHolder.getObject()</code>.</p>
<p align="justify">Now, let us see another example of Generic classes having two or more parametric types. Assume that we want to represent a class that holds a Composite object along with the elements of the composite object. We can see this kind of Composiste – children relation-ship in a number of places. For example, a Folder containing multiple files or a Window containing a number of UI Components and so on.</p>
<p align="justify">Following is the representation of the <em><strong>Container With Elements</strong></em> (<code>ContainerWithElements</code>) class holding a Container object with its children. Note that the class typed parameters have the names Container and Elements respectively for holding the Container object and its child elements.</p>
<p><strong>ContainerWithElements.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.classes;

import java.util.List;

public class ContainerWithElements
{
    private Container outerObject;
    private List innerObjects;

    public ContainerWithElements(Container outerObject, List innerObjects)
    {
        this.outerObject = outerObject;
        this.innerObjects = innerObjects;
    }

    public Container getOuterObject()
    {
        return outerObject;
    }

    public void setOuterObject(Container outerObject)
    {
        this.outerObject = outerObject;
    }

    public List getInnerObjects()
    {
        return innerObjects;
    }

    public void setInnerObjects(List innerObjects)
    {
        this.innerObjects = innerObjects;
    }

}</pre>
<p align="justify">The Client program that makes use of the above class is given below. Note the usage of the classes Folder, File, Window and Button are from the generics.classes package and they have nothing to do with the genuine java.* classes.</p>
<p><strong>ContainerWithElementsClient.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.classes;

import java.util.Arrays;

public class ContainerWithElementsClient
{
    public static void main(String[] args)
    {
        ContainerWithElements folderWithFiles
            = new ContainerWithElements(
                new Folder(), Arrays.asList(new File(), new File()));

        ContainerWithElements windowWithButtons
            = new ContainerWithElements(
                new Window(), Arrays.asList(new Button(), new Button()));
    }
}</pre>
<p align="justify">For code completeness, the declaration of the classes Folder, File, Window and Button is given below.</p>
<pre class="brush: java; title: ; notranslate">class Folder{}
class File{}

class Window{}
class Button{}</pre>
<h2 id="Writing Generic Methods">4) Writing Generic Methods</h2>
<p align="justify">In the previous section, we saw how to write <em><strong>Parameterized Classes</strong></em>. Now, let us spend time in exercising <em><strong>Parameterized Methods</strong></em> or <em><strong>Generic methods</strong></em> in this section. A Generic class containing a type parameter affects the entire class, but a generic method containing one or more type parameters affects that particular method only. So it means that a non-generic class can contain a mixture of generic and non-generic methods.</p>
<p align="justify">Following code snippet shows how to declare a Generic method.</p>
<p><strong>GenericMethods.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.methods;

public class GenericMethods
{
    static  void printType(T anyType)
    {
        System.out.println(anyType.getClass().getName());
    }

    public static void main(String[] args)
    {
        GenericMethods.printType(String.class);
        GenericMethods.printType(new String(&quot;&quot;));
    }
}</pre>
<p align="justify">If we look at the way in which a Generic method is declared, we find that the static method <code>printType()</code> has a return type void and it takes a single parameter called <code>T</code>. Here <code>T</code> stands for any <em><strong>parametric type</strong></em> which can be substituted with any of the Java types by the Clients. Since we have introduced a parameter <code>T</code>, it should be defined. But where? It should be defined in the method definition itself just before the return type of the method (&lt;T&gt;).</p>
<p align="justify">The moral is whenever we have different type parameters in a method, it should be defined in the method definition. For example, consider the following method that has two type parameters A and B and they are defined before the return type of the method separated by commas.</p>
<pre class="brush: java; title: ; notranslate"> void aGgenericMethod(A aType, B bType)
{
    // Something here.
}</pre>
<p align="justify">But the same type parameter can de used multiple number of times in the parameter list. For example, the type paramter <code>A</code> is defined once but used multiple times in the following code,</p>
<pre class="brush: java; title: ; notranslate"> void aGgenericMethod(A aType, A anotherType, B bType)
{
    // Something here.
}</pre>
<h2 id="Wildcards">5) Wildcards</h2>
<p align="justify">The following sections explain the usage of <em><strong>Wild-card character</strong></em> in Generics. For example, consider the following,</p>
<pre class="brush: java; title: ; notranslate">strObjects.add(new String(&quot;A String&quot;));
strObjects.add(new String(&quot;Another String&quot;));</pre>
<p align="justify">The above line declares an Array List with a type being the String type. The declaration says that the list (<code>strObjects</code>) in this case, can hold objects only of type <code>java.lang.String</code>. No other type is permitted other than <code>java.lang.String</code>. So, the following statements are legal as they are adding objects of type <code>java.lang.String</code>.</p>
<pre class="brush: java; title: ; notranslate">List anotherStrObjects = strObjects;</pre>
<p align="justify">Now, consider the following assignment statement which assigns the object reference <code>strObjects</code> to <code>anotherStrObjects</code>. Now <code>anotherStrObjects</code> is pointing to <code>strObjects</code> reference.</p>
<pre class="brush: java; title: ; notranslate">List</pre>
<p align="justify">The above is a perfectly legal statement as the assignment happens between the same type. Now, consider the following,</p>
<pre class="brush: java; title: ; notranslate">LObject someObject = new String(&quot;&quot;);</pre>
<p align="justify">The above statement will lead to a compiler error telling that &#8220;Cannot convert from List&lt;String&gt; to List&lt;Object&#8221;. Though <code>String</code> is a sub-class of the Object class, this type of conversion is not possible in Generics, but the following code compiles well.</p>
<pre class="brush: java; title: ; notranslate">List objects = strObjects;</pre>
<p align="justify">The reason why it is not possible to assign the List containing strings to a List that can hold Objects can be given justification as follows. The main goal of having Generic code in a program is to ensure type-safety. It means that the expected Application types and the types sent by the Clients should match. There should not be any deviation or mis-match in their types. If we go back to the code, on the left-hand side, we have a <code>List</code> that can hold Objects represented by <code>List&lt;Object&gt;</code> objects. This tells to the compiler that this List can hold objects of type <code>java.lang.Object</code>. Now we are making this object List to point to some other list whose parametric type is <code>String</code>. Though <code>String</code> is a concrete sub-class of <code>Object</code>, this assignment is not possible.</p>
<p align="justify">Let us see how to get over this problem. Consider the following code,</p>
<pre class="brush: java; title: ; notranslate">Object someObject = new String(&quot;&quot;);</pre>
<p align="justify">The character <code>'?'</code> is a wild-card character and it stands for any Java type. It can be <code>java.lang.Object</code> type or some other type. It is just a place-holder that tells that it can be assigned with any type. Considering this case, the following are now valid syntaxes.</p>
<pre class="brush: java; title: ; notranslate">List anyObjects = null;

List integers = new ArrayList();
anyObjects = integers;

List doubles = new ArrayList();
anyObjects = doubles;</pre>
<p align="justify">The above code snippet tries to assign a list of integers and a list of doubles to the reference <code>anyObjects</code>. This is perfectly legal. Another strange thing has to be considered is while adding elements into the collection. Since the type parameter for the reference anyObjects is <code>'?'</code>, no objects can be added to the collection, not even <code>java.lang.Object</code>. The only exception is that only <code>null</code> can be added to these type of collection.</p>
<pre class="brush: java; title: ; notranslate">anyObjects.add(new Integer(1)); // Wont compile
anyObjects.add(new Double(1.0)); // Wont compile

anyObjects.add(null); // This will compile.</pre>
<h2 id="Bounding the Parameterized Types">6) Bounding the Parameterized Types</h2>
<p align="justify">Generics won&#8217;t be complete if this section is not covered. It is all about <em><strong>bounding parametric types</strong></em>. Till now, we have seen parametric types operate on a single java type like <code>Object</code> or <code>String</code>. Now, let us see how the parametric types can be restricted by applying some constraints over them. For this to be illustrated, let us take a sample application called <em><strong>Animal Actions</strong></em>.</p>
<p align="justify"><em><strong>Animal Actions</strong></em> class performs various operations on a given Animal like: making them eat, sleep and run. The first constraint that we see here is that only an <code>Animal</code> object can be passed to the Animal Actions class. Let us represent the Animal class as follows.</p>
<p><strong>Animal.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.bounds;

public abstract class Animal
{
    // Some common functionalities here.
}</pre>
<p align="justify">Note that the <code>Animal</code> class is declared as abstract, meaning that some other concrete class is going to extend this <code>Animal</code> class. Another restriction that we see in Animal Actions class is that they will make the Animals to sleep, eat and run. Since these are behaviors and we may give different representations for the same, let them be modeled as interfaces. Following code shows the interface design for the behaviors,</p>
<pre class="brush: java; title: ; notranslate">package generics.bounds;

interface Sleepable
{
    public void sleep();
}

interface Runnable
{
    public void run();
}

interface Eatable
{
    public void eat();
}</pre>
<p align="justify">Let us give implementation of the above behaviors for some animal, say <code>Dog</code>. The following code snippet is for the implementation of <code>Dog</code> which conforms to eating, sleeping and running behavior.</p>
<p><strong>Dog.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.bounds;

public class Dog extends Animal implements Sleepable, Runnable, Eatable
{
    public void sleep()
    {
        System.out.println(&quot;Dog is sleeping&quot;);
    }

    public void run()
    {
        System.out.println(&quot;Dog is running&quot;);
    }

    public void eat()
    {
        System.out.println(&quot;Dog is eating&quot;);
    }</pre>
<p align="justify">Now, let us design the <em><strong>Animal Actions</strong></em> class. The restriction we have on Animal Actions class is that, we should operation on any type of object that is an Animal which can eat, sleep and run. Look into the following Animal Actions class,</p>
<p><strong>AnimalActions.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.bounds;

public class AnimalActions&lt;a&gt; { private A animal; public AnimalActions(A animal) { this.animal = animal; } public A getAnimal() { return animal; } public void setAnimal(A animal) { this.animal = animal; } public void doActions() { animal.sleep(); animal.run(); animal.eat(); } }&lt;/a&gt;</pre>
<p align="justify">The declaration of the parameterized class looks like the following,</p>
<pre class="brush: java; title: ; notranslate">public class AnimalActions</pre>
<p align="justify">Let us break down the pieces in the above declaration. The first trivial stuff that has to be noted is the declaration of the typed parameter <code>A</code> (which is for <code>Animal</code>). The next set of expressions are imposing restrictions on the typed parameter <code>A</code>. The phrase <code>'A extends Animal'</code> tells that whatever type we pass for the substitution parameter must extend/implement the Animal class/interface. The type that comes after extends can either be an interface or a class. It is illegal to mention something like the following,</p>
<pre class="brush: java; title: ; notranslate">public class AnimalActions</pre>
<p align="justify">Only <code>extends</code> keyword is used for both class as well the interface and not the <code>implements</code> keyword. If we want the parametric type to confirm by more than one classes or interfaces, then every types should be separated by the symbol <code>&amp;</code>. For example, in our case, we want some Animal to eat, sleep and run by implementing the <code>Eatable</code>, <code>Sleepable</code> and <code>Runnable</code> interface. So, we have declared something like <code>AnimalActions&lt;A extends Animal &amp; Sleepable &amp; Runnable &amp; Eatable</code>. To sum up things, the generic class declaration can be interpreted like this; it can be passed with any type that implements/extends <code>Animal</code>, <code>Sleepable</code>, <code>Runnable</code> and <code>Eatable</code> types.</p>
<p align="justify">Following code snippet makes use of the above <em><strong>Animal Actions</strong></em> class. In the below code, a new instance of <code>Dog</code> object is created and passed on to the constructor of the Animal Actions class. This is perfectly valid as the Dog class extends the Animal class and it also implements <code>Sleepable</code>, <code>Eatable</code> and <code>Runnable</code> interfaces. It then makes a call to <code>AnimalActions.doActions()</code>, thereby the execution gets directed towards <code>Dog.sleep()</code>, <code>Dog.eat()</code> and <code>Dot.run()</code>.</p>
<p><strong>AnimalActionsTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package generics.bounds;

public class AnimalActionsTest
{
    public static void main(String[] args)
    {
        AnimalActions animal = new AnimalActions(new Dog());
        animal.doActions();
    }
}</pre>
<h2 id="More on parametric bounds and wild-cards">7) More on parametric bounds and wild-cards</h2>
<p align="justify">The restriction on parametric types that is applied on class definition is also applicable to method definition. Let us move towards assignment now. Consider the following statement,</p>
<pre class="brush: java; title: ; notranslate">List animals = new ArrayList();</pre>
<p align="justify">The above is a declaration of list that essentially tells to the compiler that it can hold <code>Animal</code> objects. So the following statements is perfectly valid.</p>
<pre class="brush: java; title: ; notranslate">animals.add(new Animal()); // Fine.</pre>
<p align="justify">Assuming that <code>Animal</code> class is not abstract. Not only it is possible to add <code>Animal</code> objects but also any types that extends the <code>Animal</code> class. By having this rule in hand, it is perfectly possible to have the following statements,</p>
<pre class="brush: java; title: ; notranslate">animals.add(new Dog()); // This will work too.
animals.add(new Cat()); // This also.</pre>
<p align="justify">Even though, it is possible to add any type that extends the <code>Animal</code> class, it is not possible to have the following statement.</p>
<pre class="brush: java; title: ; notranslate">List dogs = new ArrayList();
dogs.add(new Dog()); dogs.add(new Dog());

animals = dogs; // This wont compile.</pre>
<p align="justify">The compiler will warn you telling that it is not possible to convert <code>List&lt;Dog&gt;</code> to <code>List&lt;Animal&gt;</code>. Even a type-casting on the above statement doesn&#8217;t work.</p>
<pre class="brush: java; title: ; notranslate">animals = (List&amp;lt;Animal&amp;gt;)dogs; // This won't work.</pre>
<p align="justify">Since type-casting from one type to another type is a run-time operation and during run-time there is no such existence of the types <code>List&lt;Animal&gt;</code> or <code>List&lt;Dog&gt;</code> because of erasures. All the typed-parameters won&#8217;t be available in the class-file and the above code doesn&#8217;t work.</p>
<h4>7.1) Upper Bound</h4>
<p align="justify">The solution to this situation is the usage of wild-cards along with parametric bounding. Have a look over the following declaration.</p>
<pre class="brush: java; title: ; notranslate">List animals = new ArrayList();</pre>
<p align="justify">It tells that a list is being declared with type being anything (?) that is extending the <code>Animal</code> class. Though it looks very similar to the above declaration it has some differences. The first thing is that it is now possible for the animals reference to point to a list that is holding any sub-type of <code>Animal</code> objects.</p>
<pre class="brush: java; title: ; notranslate">List dogs = new ArrayList();
dogs.add(new Dog()); dogs.add(new Dog());

animals = dogs;</pre>
<p align="justify">One important difference is that, it is not possible to add elements to the animals list, though the only exception is adding <code>null</code> elements. This is called the <em><strong>Upper Bound</strong></em> for the animals list.</p>
<h4>7.2) Lower Bound</h4>
<p align="justify">Similar to <em><strong>Upper Bounds</strong></em>, we have <em><strong>Lower Bounds</strong></em> with the following syntax,</p>
<pre class="brush: java; title: ; notranslate">List dogs = new ArrayList();</pre>
<p align="justify">This declaration tells that along with <code>Dog</code> type, all other sub-types of <code>Dog</code> is also allowed. Not any of the super-type of <code>Dog</code> can be added including <code>java.lang.Object</code>. So, if we have classes like <code>GoodDog</code> and <code>BadDog</code>, both extending the <code>Dog</code> class, then the following statements are legal.</p>
<pre class="brush: java; title: ; notranslate">dogs.add(new Dog());
dogs.add(new GoodDog());
dogs.add(new BadDog());</pre>
<h2 id="Conclusion">8) Conclusion</h2>
<p align="justify">One of the major language and syntax change in Java 5.0 is <em><strong>Java Generics</strong></em>. Through Generics, it is now possible to have a programming model that operates on some <em><strong>parametric type</strong></em> and the same model can be re-used with different types. It is important to note that there will be only one class file for the whole Generic type, unlike other programming languages (in the name of <em><strong>templates</strong></em> in C++). Generics makes use of the concept of <em><strong>Erasure</strong></em> which erases all the Generic type information during the compilation process.</p>
<ul>
<li><a href="http://www.flipkart.com/java-threads-8173665923/p/itmdyu7nnuevcmx8?pid=9788173665929&amp;affid=suthukrish" target="_blank"> <strong>Java Threads (Covers J2SE 5. 0)</strong> </a></li>
</ul>
<p align="justify">
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/08/generics-in-java-5-0/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>New Features in Java 5.0</title>
		<link>http://www.javabeat.net/2007/08/new-features-in-java-5-0/</link>
		<comments>http://www.javabeat.net/2007/08/new-features-in-java-5-0/#comments</comments>
		<pubDate>Tue, 14 Aug 2007 02:09:48 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[New Features]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=86</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction Java 5.0 comes with a bunch of useful features. In this article, we are going to have an overview of the features like Enhanced for-loop, Variable Arguments, Static Imports and Enumerations. Apart from these features, we have already published other notable features in Java 5.0, auto boxing, generics and annotations. Buy generics book [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p>Java 5.0 comes with a bunch of useful features. In this article, we are going to have an overview of the features like <em><strong>Enhanced for-loop</strong></em>, <em><strong>Variable Arguments</strong></em>, <em><strong>Static Imports</strong></em> and <em><strong>Enumerations</strong></em>. Apart from these features, we have already published other notable features in Java 5.0, <a href="http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/">auto boxing</a>, <a href="http://www.javabeat.net/2007/08/generics-in-java-5-0/">generics</a> and <a href="http://www.javabeat.net/2007/08/annotations-in-java-5-0/">annotations</a>. Buy <a href="http://www.flipkart.com/java-generics-collections-8184042167/p/itmdyusddnjsfaxn?pid=9788184042160&amp;affid=suthukrish" target="_blank">generics book</a> for detailed explanation on the concept. If you are interested in receiving the future Java mails, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</p>
<p>The sections in this article are,</p>
<h2 id="Enhanced For loop">2) Enhanced For loop</h2>
<p align="justify">We will cover the usage of <em><strong>Enhanced for-loop</strong></em> in this section. This is also referred to as for-each loop. The following code shows how to iterate over the elements in a Collection using the traditional <code>Iterator</code> interface.</p>
<p><strong>ForEachTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package foreach;

import java.util.*;

public class ForEachTest
{
	public static void main(String[] args)
	{
		List numbers = new ArrayList();
		numbers.add(1);numbers.add(2);numbers.add(3);

		Iterator numbersIterator = null;
		for(numbersIterator = numbers.iterator(); numbersIterator.hasNext();)
		{
			System.out.println(numbersIterator.next());;
		}
	}
}</pre>
<p align="justify">Though the goal of the above program is traversing over the elements in the list collection, we are depending on the <code>Iterator</code> API to achieve this. A replacement to the Iterator is the usage of Enhanced for-loop, through which it is possible to have a short and a neat code like this,</p>
<pre class="brush: java; title: ; notranslate">for(Integer number : numbers)
{
	System.out.println(number);
}</pre>
<p align="justify">Let us see how the above syntax is used to traverse over the collection. The expression before the symbol <code>':'</code> is a declaration statement which declares an <code>Integer</code> object called number for holding the individual element from the collection. The expression that follows after the symbol must be a Collection type whose elements can be iterated. Precisely, this type must implement an interface called <code>java.util.Iterable</code> which has a single method called <code>iterator()</code>. During compile-time, the compiler translates the above code which looks very similar to the following,</p>
<pre class="brush: java; title: ; notranslate">Iterator intIterator = numbers.iterator();

for(;intIterator.hasNext();)
{
	System.out.println(intIterator.next());
}</pre>
<p align="justify">Even it is possible to apply this new syntax for type Arrays. So, the following code is perfectly legal and it compiles fine.</p>
<pre class="brush: java; title: ; notranslate">int [] numbers = {10, 20, 30, 40, 50};

for(int num : numbers)
{
	System.out.println(num);
}</pre>
<p align="justify">The enhanced for-loop is just a convenience from the programmer&#8217;s point of view for iterating over the Collection. But the usage of this loop has some dis-advantages. The first one out of the two is that step-value cannot be incremented. For example, it is not possible to traverse the first element and then the thirth element and so on. And the second dis-advantage is that backward traversal is not possible.</p>
<h2 id="Variable Arguments">3) Variable Arguments</h2>
<p align="justify">Among the new features added in Java 5.0, <em><strong>Variable Arguments (var-args)</strong></em> is one of the coolest features. Before getting into this, let us see the reason in action for introducing such a feature like this. The following code snippet shows the addition of two numbers being done in the <code>testAdd()</code> method.</p>
<p><strong>VariableArgumentsTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package varargs;

public class VariableArgumentsTest
{
	static void addTest(String message, int a, int b)
	{
		int result = a + b;
		System.out.println(message + result);

	}

	public static void main(String[] args)
	{
		addTest(&quot;Addition Result is &quot;, 10, 20);
	}
}</pre>
<p align="justify">Consider that we want the <code>addTest()</code> method to add three numbers. Now, we introduce a third parameter called <code>c</code> in the method definition like this,</p>
<pre class="brush: java; title: ; notranslate">static void addTest(String message, int a, int b, int c)
{
	int result = a + b + c;
	...
}</pre>
<p align="justify">Or we can have an overloaded method that is defined with three parameters and have the original implementation there. If the number of parameter values that are going to be passed for the <code>addTest()</code> method goes on increasing, then it requires change in the existing code or possibly the addition of new overloadeded methods. The way to get over this is by using a variable arguments. Internally a variable argument is maintained as an array that can hold zero or one or more arguments of the same type. Following code snippet shows the declaration of variable arguments.</p>
<pre class="brush: java; title: ; notranslate">static void addTest(String message, int... numbers)
{
	int result = 0;
	for(int num : numbers)
	{
		result = result + num;
	}
	return result;
}</pre>
<p align="justify">Note that the type (int) is followed by three dots (often called ellipsis) and then the variable argument name. With such a declaration in hand, it is now possible to invoke the method as shown below.</p>
<pre class="brush: java; title: ; notranslate">addTest(&quot;Addition Ressult&quot;, 10, 20);     -&amp;gt; addTest(&quot;Addition&quot;, new int[]{10,20});
addTest(&quot;Addition Ressult&quot;, 10, 20, 30); -&amp;gt; addTest(&quot;Addition&quot;, new int[]{10,20, 30});
addTest(&quot;Addition Ressult&quot;);             -&amp;gt; addTest(&quot;Addition&quot;, new int[]{});</pre>
<p align="justify">All the above styles are allowed as they are internally represented as arrays. There are two major constraints in the usage of variable arguments. The first thing is a method is allowed to carry only one variable argument type. The other constraint is that a variable argument type can appear only as the last parameter in a method definition. The following shows the legal and illegal usage of variable argument types.</p>
<pre class="brush: java; title: ; notranslate">static void test(int... a, String... b) -&amp;gt; Invalid, more than one variable argument type.
static void test(int... a, int... b)    -&amp;gt; Invalid, more than one variable argument type.
static void test(int... a, int b, int c)-&amp;gt; Invalid, Variable argument type must be the last parameter.
static void test(int a, int... b, int c)-&amp;gt; Invalid, Variable argument type must be the last parameter.
static void test(int a, int... b)       -&amp;gt; This is legal.
static void test(int... a)              -&amp;gt; This is also legal.</pre>
<h2 id="Static Imports">4) Static Imports</h2>
<p align="justify"><em><strong>Static Imports</strong></em> is all about importing all the static Entities &#8211; like static classes, static methods and static objects and directly accessing them in code. For example, let us consider that you have a class like this,</p>
<p><strong>StaticTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package staticimport;

public class StaticTest
{
	public static final Object STATIC_OBJECT = new Object();

	public static Object getStaticObbject()
	{
		return STATIC_OBJECT;
	}

	public static class StaticClass
	{

	}
}</pre>
<p align="justify">The above class is in a package called <code>staticimport</code> and it has a public static object called <code>STATIC_OBJECT</code>, a static method called <code>getStaticObject()</code> and a static inner class called <code>StaticClass</code>. Now let us see how to make use of static imports for accessing these static objects directly. Consider the following client program,</p>
<p><strong>StaticTestClient.java</strong></p>
<pre class="brush: java; title: ; notranslate">package staticimport.client;

import static staticimport.StaticTest.StaticClass;
import static staticimport.StaticTest.getStaticObbject;
import static staticimport.StaticTest.STATIC_OBJECT;

public class StaticTestClient {

	public static void main(String[] args) {

		System.out.println(&quot;Usage of a static class&quot;);
		StaticClass staticClassObject = new StaticClass();

		System.out.println(&quot;Usage of a static method&quot;);
		Object fromAStaticMethod = getStaticObbject();

		System.out.println(&quot;Usage of a static object&quot;);
		Object someStaticObject = STATIC_OBJECT;

	}
}</pre>
<p align="justify">If you note the syntax of static imports, the <code>static</code> keyword follows after the import keyword. Only Static classes, static methods and static objects can be imported in this manner. Suppose, if you try to import a type that is not static, then the compiler will warn you telling that &#8220;The import cannot be resolved&#8221;, though it should give a descriptive warning telling that the type you are trying to import something which is not static.</p>
<p align="justify">Following example makes use of the APIs in the java packages. More specifically it imports all the static objects (members, objects and static classes) defined in <code>System</code> and <code>Math</code> class.</p>
<p><strong>StaticTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package staticimport.client;

import static java.lang.Math.*;
import static java.lang.System.*;

public class StaticTest {

	public static void main(String[] args)
	{
		gc();
		out.println(&quot;Testing static object&quot;);
		out.println(&quot;max of 10 and 20 is &quot; + max(10, 20));
	}
}</pre>
<h2 id="Enumerations">5) Enumerations</h2>
<p align="justify">Let us conclude this article by having a look at <em><strong>Enumerations</strong></em> (or <em><strong>Enums</strong></em>). In Java, Enum is a type, like a class or an interface. If Classes are used to represent objects, interfaces for behavior, then Enumerations are used to define range-based constants. For example, consider the following class that will calculate the population of a country when given the country name.</p>
<p><strong>PopulationCalculator.java</strong></p>
<pre class="brush: java; title: ; notranslate">package enums;

public class PopulationCalculator
{
	public static double calculatePopulation(String countryName)
	{
		double population = 0.00;

		if(countryName.equals(&quot;India&quot;))
		{
			// Set Indian population here.
		}else if (countryName.equals(&quot;Australia&quot;))
		{
			// Set population for Aussies here.
		}else if (countryName.equals(&quot;England&quot;))
		{
			//Set population value for England here.
		}
		return population;
	}
}</pre>
<p align="justify">The problem in the above code is with the input parameter <code>countryName</code>. Since the countryName is represented as a string, care should be taken in the very first line to ascertain the availability of such a country. What if the client passes something like &#8220;ABCDEF&#8221; or an empty string (&#8220;&#8221;) or even null for the country name? In all these cases, we end up in some kind of un-expected results at the run-time. We would feel that it would be better if the same error is captured during the compile-time itself. Here comes the concept of Enum which is any other type like Object, String or some other thing.</p>
<p align="justify">Following is the declaration of Enum called Country which takes the possible values of <code>India</code>, <code>Australia</code> and <code>England</code>.</p>
<p><strong>Country.java</strong></p>
<pre class="brush: java; title: ; notranslate">package enums;

public enum Country
{
	INDIA,

	AUSTRALIA,

	ENGLAND,

}</pre>
<p align="justify">The keyword <code>enum</code> precedes the name of the Enum, in this case <code>Country</code>. Note that declaration of the various country names like <code>India</code>, <code>Australia</code> and <code>England</code> separated by commas. Internally, an Enum is represented by a class and the objects within it will be treated as <code>public</code>, <code>static</code> and <code>final</code>. So the above <code>Country</code> enum will internally look like this,</p>
<p><strong>Country.java</strong></p>
<pre class="brush: java; title: ; notranslate">package enums;

public class Country extends java.lang.Enum
{
	public static final Country INDIA = new Country();

	public static final Country AUSTRALIA = new Country();

	public static final Country ENGLAND = new Country();

}</pre>
<p align="justify">Note that by default all the Enum classes extends <code>java.lang.Enum</code> class. And the restriction is that they cannot be extended. So Enums are implicitly treated as final classes, even though they can implement Interfaces. Now, let us modify the above Population Calculator class to make use of <code>Country</code> Enum instead of a string. Following is the code for the same.</p>
<p><strong>PopulationCalculator.java</strong></p>
<pre class="brush: java; title: ; notranslate">package enums;

public class PopulationCalculator
{
	public static double calculatePopulation(Country country)
	{
		double population = 0.00;

		if(country.equals(Country.INDIA))
		{
			// Set Indian population here.
		}else if (country.equals(Country.AUSTRALIA))
		{
			// Set population for Aussies here.
		}else if (country.equals(Country.ENGLAND))
		{
			//Set population value for England here.
		}
		return population;
	}
}</pre>
<p align="justify">Now, since the <code>calculatePopulation()</code> method is accepting a type <code>Country</code> which is of type Enum, the client can pass only any of the defined Object in the Enum, thereby ensuring type-safeness. Since all custom Enum classes extend <code>java.lang.Enum</code> class, some of the useful methods like <code>Enum.values()</code> and <code>Enum.ordinal()</code> are automatically available to the <code>Country</code> Enum class. Have a look at the following sample class.</p>
<p><strong>EnumTest.java</strong></p>
<pre class="brush: java; title: ; notranslate">package enums;

public class EnumTest {

	public static void main(String[] args) {

		Country[] countries = Country.values();

		for(Country country : countries){
			System.out.println(country.toString() + &quot;:
				Oridinal Value-&amp;gt;&quot; + country.ordinal());
		}

}</pre>
<p align="justify">The call to <code>Country.values()</code> will return an Array of Country values with the values defined within the Country Enum. The method <code>Country.ordinal()</code> will return an index that tells the position of the enum object.</p>
<h2 id="Conclusion">6) Conclusion</h2>
<p align="justify">This article covered some of the new features available in Java 5.0 like Enhanced For loop, Variable Arguments, Static Imports and Enumerations along with plenty of samples. Each of these new features finds its appropriate usage based on the requirements. Applications can make use of the new features in an optimal way and thereby ensure that the code is simple and efficient.</p>
<p>Javabeat has published many of the good articles related to Java 1.5 version. This list will help you to learn some of the notable features introduced with the version 1.5, please have a look on these articles when time permits. Don’t forget to leave your feedback on the comments section. This helps us to provide better content for you.</p>
<ul>
<li><a href="http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/" target="_blank">Autoboxing in Java 5.0</a></li>
<li><a title="Annotations in Java 5.0" href="http://www.javabeat.net/2007/08/annotations-in-java-5-0/" rel="bookmark">Annotations in Java 5.0</a></li>
<li><a href="http://www.javabeat.net/2007/08/generics-in-java-5-0/">Generics in Java 5.0</a></li>
<li><a href="http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/">How to use enum in switch?</a></li>
</ul>
<p>The above article would provide the higher level of understanding on each concept. There are many other great features introduced in the Java 1.5 version. If you would like to know all the features in detail, please buy <a href="http://www.flipkart.com/java-007063677x/p/itmczyz72sxshaba?pid=9780070636774&amp;affid=suthukrish" target="_blank">Java Complete Reference</a>, which is the most popular book and released first when this version is announced. Hope this helps you!!</p>
<p><strong>If you would like to receive future mails on Java articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/08/new-features-in-java-5-0/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>AutoBoxing in Java 5.0</title>
		<link>http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/</link>
		<comments>http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/#comments</comments>
		<pubDate>Sun, 12 Aug 2007 02:08:33 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[AutoBoxing]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=83</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1)Introduction In the latest version of J2SE 5.0 released by Sun, Autoboxing is one of the new feature. Before J2SE 5.0, working with primitive types required the repetitive work of converting the primitive types into wrapper classes and vice &#8211; versa. Sometimes the purpose of conversion is just for some API call, after which the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1)Introduction</h2>
<p>In the latest version of J2SE 5.0 released by Sun, <strong>Autoboxing</strong> is one of the new feature. Before <a href="http://www.javabeat.net/2007/08/new-features-in-java-5-0/">J2SE 5.0</a>, working with primitive types required the repetitive work of converting the primitive types into wrapper classes and vice &#8211; versa. Sometimes the purpose of conversion is just for some API call, after which the results have to be converted into original form which is very frustrating . <strong><span style="color: #000080;">Auto-boxing and Auto-Unboxing enables the primitive types to be converted into respective wrapper objects and the other way around</span></strong>.This article gives some insight about the importance of this new feature and how it can be used in the real-world programming. The following are some of the popular books available for learning Java 1.5</p>
<ul>
<li><a href="http://www.flipkart.com/java-1-5-tiger-8173668477/p/itmdyu7zt7qxsgpe?pid=9788173668470&amp;affid=suthukrish" target="_blank">Java 1.5 Tiger: A Developer’s Notebook</a></li>
<li><a href="http://www.flipkart.com/java-cookbook-8173669368/p/itmdyu7zvbs3m4dh?pid=9788173669361&amp;affid=suthukrish" target="_blank">Java Cookbook</a></li>
</ul>
<h2>2)Boxing/Unboxing</h2>
<p>Let&#8217;s take a small example of incrementing the value of Integer Object for understanding the concept of Boxing/Unboxing.</p>
<pre class="brush: java; title: ; notranslate">
Before Java 5
int intPrimitive = intObject.intValue();
intPrimitive++;
intObject = new Integer(intPrimitive);

Using Java 5

Integer intObject = new Integer(10);
intObject++;
</pre>
<p>The output for the above examples will be same. In the first example we are creating an Integer object, unwrapping it to primitive value,<br />
incrementing the primitive value, re-wrapping it to Integer object again.</p>
<p>In the second example when the compiler encounters the line intObject++ compiler unwraps Integer object to primitive type, increments it and rewraps to Integer Object again,So When the compiler got to the line intObject++; it substitues the code which will be something like this:</p>
<pre class="brush: java; title: ; notranslate">Integer.valueOf(intObject.intValue()+1);

	or

	int intPrimitive = intObejct.intValue();
	intPrimitive++;
	intObject = new Integer(intPrimitive);</pre>
<p>Below example&#8217;s show different ways of Boxing/Unboxing.</p>
<pre class="brush: java; title: ; notranslate">Boolean isValid = false;		// Boxing

		Short shortObject = 200;	        // Boxing

		if(shortObject list = new ArrayList();
	          for(int i = 0; i &amp;amp;lt; 10; i++){
        	     list.add(i); 		       // Boxing
          	}</pre>
<h2>3)How Overloading works for Boxing/Unboxing ?</h2>
<ul>
<li>General Rule: Arguments are implicitly widened to match method parameters.</li>
</ul>
<p>Lets assume that we are having a function which takes an int as paratmeter.</p>
<pre class="brush: java; title: ; notranslate">public void testWidening(int i){
	// Business Logic
	}

	byte b = 25;
	testWidening(b);</pre>
<p>Now instead of passing int as an argument if we pass byte or short as arguments then these arguments are implicitly widened to match the testWidening method that takes an int.</p>
<h3>Overloading with Boxing</h3>
<h3>Scenario 1: overloaded functions which take int and Integer as parameters.</h3>
<pre class="brush: java; title: ; notranslate">void testWidening(int j){
	    	System.out.println(&amp;quot;method call for primitive int&amp;quot;);
    	    }
   	    void testWidening(Integer k){
		System.out.println(&amp;quot;method call for Integer Object&amp;quot;);
    	    }

	    int i = 30;
            new Test().testWidening(i);

           O/P: method call for primitive int</pre>
<p>Pretty straight forward output, int is passed as an argument and the function which is taking int as parameter has been invoked.</p>
<h3>Scenario 2: overloaded functions which take long and Integer as parameters.</h3>
<pre class="brush: java; title: ; notranslate">void testWidening(long j){
 	    	System.out.println(&amp;quot;method call for primitive long&amp;quot;);
	    }
	    void testWidening(Integer k){
	    	System.out.println(&amp;quot;method call for Integer Object&amp;quot;);
	    }

	    O/P: method call for primitive long</pre>
<p><span style="text-decoration: underline;">Since pre-existing/older versions of code should function the way it used to be, the compiler will always choose the older conversion of widening rather then the new one</span>.Here the function which takes long as a parameter is choosen over the function which takes Integer as a parameter.</p>
<h3>Scenario 3: overloaded functions which take Long and Integer as parameters.</h3>
<pre class="brush: java; title: ; notranslate">void testWidening(Long j){
 	   	System.out.println(&amp;quot;method call for Long Object&amp;quot;);
	    }
	    void testWidening(Integer k){
	    	System.out.println(&amp;quot;method call for Integer Object&amp;quot;);
	    }
	    O/P: method call for Integer Object</pre>
<p>As expected now the method which is taking Integer object as parameter has been called over the method which is taking Long object as parameter.</p>
<h3>Scenario 4: overloaded functions which take int and long as parameters and argument is an Integer object.</h3>
<pre class="brush: java; title: ; notranslate">void testWidening(int i){
        		System.out.println(&amp;quot;in int method&amp;quot;);
    		}
    		void testWidening(long j){
        		System.out.println(&amp;quot;in long method&amp;quot;);
    		}

        	new Test().testWidening(new Integer(10));

		O/P: in int method</pre>
<p>The above example shows how Unboxing is done in Java 5. Here we are passing Integer object as an argument and the method which takes int as parameter has been invoked.</p>
<h3>Widening Reference Variables</h3>
<pre class="brush: java; title: ; notranslate">class Shape{
        	//common methods
    	}
	public class Rectangle extends Shape{
    		public void testWidening(Shape s){
	        	System.out.println(&amp;quot;Here I am&amp;quot;);
    		}
		public static void main(String a[]){
		    Rectangle r = new Rectangle();
		    r.testWidening(r);
    		}
	}
	O/P: Here I am</pre>
<p>Here the testWidening method needs Shape object, and Rectangle IS-A Shape. Now let&#8217;s look this example.</p>
<pre class="brush: java; title: ; notranslate">void testWidening(Long i){
        	System.out.println(&amp;quot;method call for Long Object&amp;quot;);
    	}
    	public static void main(String a[]){
        	test t = new test();
        	t.testWidening(new Integer(10));
    	}
	O/P: Compile Time Error</pre>
<p>It&#8217;s not legal to widen from one wrapper class to another, The reason is all the wrapper classes like BigDecimal, BigInteger, Byte, Double, Float,Integer, Long, Short extend Number class and its not valid to say Integer IS-A Long.</p>
<h3>3)How ==, !=, &lt;=, &gt;= works for Boxing/Unboxing ?</h3>
<p>Let&#8217;s look at the below example&#8217;s.</p>
<ul>
<li>Example for ==</li>
</ul>
<pre class="brush: java; title: ; notranslate">Integer intObject1 = 100;
        Integer intObject2 = 100;
        Integer intObject3 = 128;
        Integer intObject4 = 128;

        if(intObject1 == intObject2)
            System.out.println(&amp;quot;intObject1 and intObject2 are equal&amp;quot;);
        else
            System.out.println(&amp;quot;intObject1 and intObject2 are not equal&amp;quot;);

         if(intObject3 == intObject4)
            System.out.println(&amp;quot;intObject3 and intObject4 are equal&amp;quot;);
        else
            System.out.println(&amp;quot;intObject3 and intObject4 are not equal&amp;quot;);

	O/P: intObject1 and intObject2 are equal
	     intObject3 and intObject4 are not equal</pre>
<p>General guess would be false in both cases.</p>
<p>Here there is a difference in the output&#8217;s of two if statements because in order to save memory when primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object.<span style="text-decoration: underline;"><strong> But for some special cases, the JVM reuses the same object, two instances of the following wrapper objects will always be == when their primitive values are the same.</strong></span></p>
<ul>
<li>Boolean</li>
<li>Byte</li>
<li>Character from \u0000 to \u007f (7f is 127 in decimal)</li>
<li>Short and Integer from -128 to 127</li>
</ul>
<ul>
<li>Example for !=</li>
</ul>
<pre class="brush: java; title: ; notranslate">if(intObject1 != intObject2)
            System.out.println(&amp;quot;intObject1 and intObject2 are not equal&amp;quot;);
        else
            System.out.println(&amp;quot;intObject1 and intObject2 are equal&amp;quot;);
        if(intObject3 != intObject4)
            System.out.println(&amp;quot;intObject3 and intObject4 are not equal&amp;quot;);
        else
            System.out.println(&amp;quot;intObject3 and intObject4 are equal&amp;quot;);
	O/P:
	intObject1 and intObject2 are equal
	intObject3 and intObject4 are not equal</pre>
<p>The ouput is as expected, Since the values of intObject1 and intObject 2 are below 128, they are considered as equal and intObject3 and intObject4 are considered as not equal.</p>
<ul>
<li>Example for &lt;= and &gt;=</li>
</ul>
<pre class="brush: java; title: ; notranslate">Integer intObject1 = 100;
        Integer intObject2 = 101;
        Integer intObject3 = 128;
        Integer intObject4 = 129;

        if(intObject1  intObject2&amp;quot;);
        if(intObject4 &amp;amp;gt;= intObject3)
            System.out.println(&amp;quot;intObject4 is &amp;amp;gt;= intObject3&amp;quot;);
        else
            System.out.println(&amp;quot;intObject4 is &amp;amp;lt; intObject3&amp;quot;);
	O/P:
	intObject1 is = intObject3</pre>
<p>This time we have changed 2nd and 4th declarations from Integer to Int still the output is the same.</p>
<pre class="brush: java; title: ; notranslate">Integer intObject1 = 100;
        int 	intObject2 = 101;
        Integer intObject3 = 128;
        int 	intObject4 = 129;

        if(intObject1  intObject2&amp;quot;);
        if(intObject4 &amp;amp;gt;= intObject3)
            System.out.println(&amp;quot;intObject4 is &amp;amp;gt;= intObject3&amp;quot;);
        else
            System.out.println(&amp;quot;intObject4 is &amp;amp;lt; intObject3&amp;quot;);
	O/P:
	intObject1 is = intObject3</pre>
<h3>Conclusion</h3>
<p><span style="color: #000080;">This <em>new feature in J2SE 5.0</em> has both advantages and disadvantages, it all depends on where and how are we using the feature.</span> It is recommended by SUN to use them only when there is an “impedance mismatch” between reference types and primitives, for example, when you have to put numerical values into a collection. It is not appropriate to use <strong>autoboxing</strong> and <strong>unboxing</strong> for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; <strong>autoboxing</strong> and <strong>unboxing</strong> blur the distinction between primitive types and reference types, but they do not eliminate it.</p>
<p>Javabeat has published many of the good articles related to Java 1.5 version. This list will help you to learn some of the notable features introduced with the version 1.5, please have a look on these articles when time permits. Don&#8217;t forget to leave your feedback on the comments section. This helps us to provide better content for you.</p>
<ul>
<li><a href="http://www.javabeat.net/2007/08/new-features-in-java-5-0/">New features in Java 5.0</a></li>
<li><a title="Annotations in Java 5.0" href="http://www.javabeat.net/2007/08/annotations-in-java-5-0/" rel="bookmark">Annotations in Java 5.0</a></li>
<li><a href="http://www.javabeat.net/2007/08/generics-in-java-5-0/">Generics in Java 5.0</a></li>
<li><a href="http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/">How to use enum in switch?</a></li>
</ul>
<p><span style="color: #000080;">The above article would provide the higher level of understanding on each concept. There are many other great features introduced in the Java 1.5 version. If you would like to know all the features in detail,</span> please buy <a href="http://www.flipkart.com/java-1-5-tiger-8173668477/p/itmdyu7zt7qxsgpe?pid=9788173668470&amp;affid=suthukrish" target="_blank">Java 1.5 Tiger: A Developer’s Notebook</a>, which is the most popular book and released first when this version is announced. Hope this helps you!!</p>
<p><span style="color: #000080;"><strong>If you would like to receive future mails on Java articles, please subscribe <a href="http://www.javabeat.net/subscribe/"><span style="color: #000080;">here</span></a>.</strong></span></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/08/autoboxing-in-java-5-0/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Annotations in Java 5.0</title>
		<link>http://www.javabeat.net/2007/08/annotations-in-java-5-0/</link>
		<comments>http://www.javabeat.net/2007/08/annotations-in-java-5-0/#comments</comments>
		<pubDate>Sat, 11 Aug 2007 02:05:42 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[Annotations]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=80</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction Annotations in Java is all about adding meta-data facility to the Java Elements. Like Classes, Interfaces or Enums, Annotations define a type in Java and they can be applied to several Java Elements. Tools which will read and interpret the Annotations will implement a lot of functionalities from the meta-information obtained. For example, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>1) Introduction</h2>
<p align="justify">Annotations in Java is all about adding meta-data facility to the Java Elements. Like Classes, Interfaces or Enums, Annotations define a type in Java and they can be applied to several Java Elements. Tools which will read and interpret the Annotations will implement a lot of functionalities from the meta-information obtained. For example, they can ensure the consistency between classes, can check the validity of the paramters passed by the clients at run-time and can generate lot of base code for a project. This article provides you a complete guide detailing the various aspects of Annotations. The topics covered in this article are as follows,</p>
<blockquote><p>Buy <a href="http://www.flipkart.com/java-generics-collections-8184042167/p/itmdyusddnjsfaxn?pid=9788184042160&amp;affid=suthukrish" target="_blank">Java Generics</a> from FlipKart.com (<strong>Java Generics and Collections</strong> covers everything from the most basic uses of generics to the strangest corner cases. It teaches you everything you need to know about the collections libraries, so you’ll always know how and when to use each collection for any given task.)</p></blockquote>
<h2 id="Java Annotations">2) Java Annotations</h2>
<h3>2.1) Introduction</h3>
<p align="justify">Java, being a wonderful object-oriented language provided support for <em><strong>Annotations</strong></em> starting from 5.0. This feature was added to Java 5.0 as a result of the JSR 175 namely &#8220;A Metadata Facility for the JavaTM Programming Language&#8221;. Annotations in Java can be seen elsewhere in a program. It can be seen in class declaration, method declaration, field declaration etc. The added Annotation to <em><strong>Java Elements</strong></em> have proven themselves to be considerably useful in many instances. Consider the following class definition,</p>
<p><strong>Employee.java</strong></p>
<pre class="brush: java; title: ; notranslate">final class Employee
	{
		private String name;
		private String id;

		// Getters and setters for Employee class.
	}</pre>
<p align="justify">The above is a definition of a class, <code>Employee</code>. It can be noted that the class declaration is preceded with the <code>final</code> keyword which tells that this class cannot be sub-classed. So, the introduction of the <code>final</code> keyword adds some additional information (or adds some constraints) over the class definition telling that no other class in the word can extend the <code>Employee</code> class. Therefore, the <code>final</code> keyword forms a part in providing meta-data information in the class definition. So, this is one variation of Annotation. Annotations are generally a way to add meta-data information to an element (an element can be a class, method, field, or anything) and these meta-data are processed by the tools (compilers, javadoc, etc.). Annotations are differentiated from other elements like class, interface etc., by preceding an <code>'@'</code> symbol before it.</p>
<p align="justify">An annotation definition looks like the following,</p>
<p><strong>TestAnnotation.java</strong></p>
<pre class="brush: java; title: ; notranslate">public @interface TestAnnotation
	{
		// Property Definition here.
	}
</pre>
<p align="justify">Don&#8217;t get confused with the <code>interface</code> keyword. It has nothing to do with annotations. <code>'@'</code> along with interface is the start of the annotation definition and <code>TestAnnotation</code> in the above case is the name of the Annotation. Whether annotations can be applied to class (a class-level annotation), or a method (method-level annotation) or a field (field-level annotation) is specified in the declaration of the annotation itself. This is referred to as <em><strong>Annotating an Annotation</strong></em> itself.</p>
<p align="justify">The Meta-Annotations that would be covered in the forthcoming sections are,</p>
<ul>
<li>Target Annotation</li>
<li>Retention Annotation</li>
</ul>
<h3>2.2) Target Annotation</h3>
<p align="justify">For example, if the case is that <code>@TestAnnotation</code> annotation can only be applied to methods, then there is a Meta-Annotation (meta-data about meta-data) which tells for which element type this annotation is applicable. For example, the following is the declaration of the <code>@TestAnnotation</code> annotation along with some meta-data that states the elements that this annotation can be applied to.</p>
<p><strong>TestAnnotation.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target(ElementType.METHOD)
	public @interface TestAnnotation
	{
		// Property Definitions here.
	}</pre>
<p align="justify">From the above, we can see that the Annotation <code>@TestAnnotation</code> is annotated with <code>@Target</code>. This kind of Annotation Chaining is always possible. The target element tells that the <code>@TestAnnotation annotation</code> can be applied only to methods and not to any other element types. The argument to <code>@Target</code> Annotation can be one from the possible set of values of any Java Element, which is defined in a well-defined Enum called <code>ElementType</code>. Here are the possible values taken by this Enum,</p>
<ul>
<li>TYPE – Applied only to Type. A Type can be a Java class or interface or an Enum or even an Annotation.</li>
<li>FIELD – Applied only to Java Fields (Objects, Instance or Static, declared at class level).</li>
<li>METHOD – Applied only to methods.</li>
<li>PARAMETER – Applied only to method parameters in a method definition.</li>
<li>CONSTRUCTOR – Can be applicable only to a constructor of a class.</li>
<li>LOCAL_VARIABLE – Can be applicable only to Local variables. (Variables that are declared within a method or a block of code).</li>
<li>ANNOTATION_TYPE – Applied only to Annotation Types.</li>
<li>PACKAGE – Applicable only to a Package.</li>
</ul>
<h3>2.3) Retention Annotation</h3>
<p align="justify">Another commonly used Meta-data for an Annotation is the <em><strong>Retention Policy</strong></em>. Assume that we have some Annotations defined in the source code. We have a mechanism through which we can say that to what extent the Annotations should be retained. The three possible ways of telling this are,</p>
<ul>
<li>Retain the Annotation in the Source Code only</li>
<li>Retain the Annotation in the Class file also.</li>
<li>Retain the Annotation Definition during the Run-time so that JVM can make use of it.</li>
</ul>
<p align="justify">The Annotation that is used to achieve this is <code>@Retention</code> and it takes a possible values of <code>SOURCE</code>, <code>CLASS</code> and <code>RUNTIME</code> defined in <code>RetentionPolicy</code> Enumeration. For example, if we want to retain the <code>@TestAnnotation</code> information till the class file, we can define something like this,</p>
<p><strong>TestAnnotation.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target(ElementType.METHOD)
	@Retention(RetentionPolicy.CLASS)
	public @interface TestAnnotation
	{
		// Property Definitions here.
	}</pre>
<h2 id="Built-in Annotations in Java">3) Built-in Annotations in Java</h2>
<p align="justify">There are some pre-defined annotations available in the Java Programming language. They are,</p>
<ul>
<li>Override</li>
<li>Deprecated</li>
<li>SuppressWarnings</li>
</ul>
<h3>3.1) The @Override Annotation</h3>
<p align="justify">The syntax of the <code>@Override</code> annotation is as follows,</p>
<p><strong>Override.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Retention(RetentionPolicy.CLASS)
	@Target(ElementType.RUNTIME)
	public @interface Override
	{
	}
</pre>
<p align="justify"><code>@Override</code> annotation essentially tells to the compiler that, whenever such an annotation is defined in a method of some class, then that method must be an overridden method. If not, then the compilers can report them as errors. Consider the following sample which explains this,</p>
<p><strong>Employee.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class Employee
	{
		protected void startWork()
		{
			// Code that will start to do some work.
		}

		protected void endWork()
		{
			// Code to end the work.
		}
	}</pre>
<p><strong>Manager.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class Manager extends Employee
	{

		@Override
		protected void startWork()
		{
			// Code that will start to do some work.
		}

		@Override
		protected void endWork()
		{
			// Code to end the work.
		}
	}</pre>
<p align="justify">In the above sample code, we have a class called Employee with two methods namely <code>startWork()</code> and <code>endWork()</code>. These methods have been marked as <code>protected</code> so that sub-classses can override them by providing their own functionality. A class, <code>Manager</code> is created and the methods are overriden in the sub-class. At this point, we have to note one key issue. The methods <code>startWork()</code> and <code>endWork()</code> has been annotated with <code>@Override</code> annotation. This tells to the compiler that the method that is annotated with <code>@Override</code> is an overridden method. So, the compiler immediately climbs up to the base class to find the existence of such a method. If no such method is found in the base class, then the compiler can report an error message.</p>
<p align="justify">The major aim of introducing this annotation <code>@Override</code> is to catch the errors that programmers might make when overriding a method in the sub-class. For example, consider the following sample code,</p>
<p><strong>DefaultTableCellEditor.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class DefaultTableCellEditor implements TableCellEditor
	{
		public Component getTableCellEditorComponent (JTable table,
                                             Object value,
                                             boolean isSelected,
                                             int row,
                                             int column)
		{
			// Default functionality goes here.
		}
	}</pre>
<p align="justify">If the functionality of the <code>getTableCellEditorComponent()</code> has to be overriden, then a new class has to be created by extending the <code>DefaultTableCellEditor</code> as shown below,</p>
<p><strong>MyCustomizedTableCellEditor.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class MyCustomizedTableCellEditor extends DefaultTableCellEditor
	{
		public Component getTableCellEditorComponet(JTable table,
                                             Object value,
                                             boolean isSelected,
                                             int row,
                                             int column){

			// My customized functionality goes here.
		}
	}</pre>
<p align="justify">The above code compiles and run fine, but not with the expected behavior because of the fact that when re-defining the method in the sub-class the method name has been wrongly spelled (<code>getTableCellEditorComponet()</code> instead of <code>getTableCellEditorComponent()</code>). Developers would have wasted their energy and time in debugging what was wrong with the code and why the expected behavior wasn&#8217;t the customized functionality. These kind of errors can be found at the compile-time rather than at the run-time, if the annotation <code>@Override</code> is applied on the re-defined method in the sub-class. If the method is annotated with <code>@Override</code> and if there is an mismatch in the method name or in the argument list, then the compiler will immediately report an error message like,</p>
<p align="justify">&#8220;The method getTableCellEditorComponet of type &#8216;MyCustomizedTableCellEditor&#8217; must override a super-class method&#8221;.</p>
<h3>3.2) The @SuppressWarnings Annotation</h3>
<p align="justify">With the concept of Generics starting from Java 5.0, references to any of the Collection types should be parameterized. Else the compiler will issue a warning message. For example, consider the following legacy code which makes use of a raw List type,</p>
<p><strong>LegacyCode.java</strong></p>
<pre class="brush: java; title: ; notranslate">package builtin.suppress;

	import java.util.*;

	public class LegacyCode
	{
		public static List toList(Object[] array)
		{
			return Arrays.asList(array);
		}
	}</pre>
<p align="justify">If the code gets compiled by using a Java 5 Compiler, then we would probably see a message something very similar to this.</p>
<p align="justify">&#8220;List is a raw type. References to generic type List&lt;E&gt; should be parameterized&#8221;.</p>
<p align="justify">The compiler suggests not to use raw type for Collection without being parameterized with some type. For getting rid of this warning message, one can define the return type like List&lt;Object&gt; thereby making the compiler happy. Assume the case of legacy projects when its get compiled by a Java 5.0 compiler. We can see numerous of warning like this. It is highly impossible to go and fix everywhere. Consider the case where a project is depending on a third-party library, in which case the dependant source code cannot be changed. The solution for this problem is to make use of <code>@SuppressWarnings</code> Annotation. The following shows the definition of a <em><strong>Suppress Warning Annotation</strong></em>,</p>
<p><strong>SuppressWarnings.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
	@Retention(RetentionPolicy.SOURCE)
	public @interface SuppressWarnings
	{
		String[] value();
	}</pre>
<p align="justify">Note that Suppress Warnings can be used on various Java elements like Class/Interface, Method, Constructor etc. When applied on any of the Java Elements along with a value, it provides a hint to the Compiler to turn-off the warnings. Consider the following code,</p>
<pre class="brush: java; title: ; notranslate">@SuppressWarnings(&quot;unchecked&quot;)
	public static List toList(Object[] array)
	{
		return Arrays.asList(array);
	}</pre>
<p align="justify">The above code provides a hint to the compiler to suppress the unchecked warnings. Following is another example of Suppress Warnings. We know that it is a good practice to provide a <em><strong>Serial Version Identifier</strong></em> for a class that implements the <code>Serializable</code> interface. Consider the following code,</p>
<p><strong>LegacyCode.java</strong></p>
<pre class="brush: java; title: ; notranslate">package builtin.suppress;

	import java.io.Serializable;
	import java.util.*;

	public class LegacyCode implements Serializable
	{
		@SuppressWarnings(&quot;unchecked&quot;)
		public static List toList(Object[] array)
		{
			return Arrays.asList(array);
		}
	}</pre>
<p align="justify">The compiler will warn saying that for a <code>Serializable</code> class, there should be a definition of <em><strong>Serial Version Identifier</strong></em> like this :&#8221;The serializable class LegacyCode does not declare a static final serialVersionUID field of type long&#8221;. This can be suppressed (although its not a good practice) by using the following Annotation.</p>
<p><strong>LegacyCode.java</strong></p>
<pre class="brush: java; title: ; notranslate">@SuppressWarnings(&quot;serial&quot;)
	public class LegacyCode implements Serializable
	{

	}</pre>
<p align="justify">Note that in the above case the Annotation is applied in the class-level.</p>
<h3>3.3) The @Deprecated Annotation</h3>
<p align="justify">The Interfaces and the Classes in an Application get updated every now and then. Interfaces used by the Clients may undergo so many revisions in the form of new methods being added and existing methods being removed or updated. Imagine the case where a method defined in a class or an interface has now become obsolete and we should warn the Client Applications not to make use of them. One dangerous way is to remove the method itself from the Interface. But this solution has a huge impact on the code that is dependant on this interface. Another elegant way is to mark the old method as deprecated which informs the client not to use this method anymore because in the future versions this old method may not be supported. Clients may prepare themselves not to depend on the old method anymore.</p>
<p align="justify">For example, consider the following code,</p>
<p><strong>MyOldClass.java</strong></p>
<pre class="brush: java; title: ; notranslate">package builtin.deprecated;

	public class MyOldClass
	{
		/**
		* This method has become obsolete. Client Applications now can
		* depend on
		* {@link #myAlternativeMethod()} to achieve the same affect.
		*/
		@Deprecated
		public void myDeprecatedMethod()
		{
			// Obsolete code here.
		}

		public void myAlternativeMethod()
		{
			// Revised code here.
		}
	}</pre>
<p align="justify">The class <code>MyOldClass</code> has a method <code>myDeprecatedMethod()</code> which is tagged as <em><strong>Deprecated</strong></em>. Now if any of the Client code tries to access this method, then the following warning message is issued by the compiler.</p>
<p align="justify">&#8220;The method myDeprecatedMethod() from the type MyOldClass is deprecated&#8221;.</p>
<p align="justify">It is always nice to mention the alternate ways in the JavaDoc itself. For example, the JavaDoc for <code>myDeprecatedMethod()</code> method suggests to use the method <code>myAlternativeMethod()</code> as an alternative.</p>
<h2>4) User-defined Annotations</h2>
<p align="justify">In this section, we shall see how to annotate objects that we may come across in day-to-day life. Imagine that we want to persistent object information to a file. An Annotation called <code>Persistable</code> can be used for this purpose. An important thing is that we want to mention the file in which the information will get stored. We can have a property called <code>fileName</code> within the declaration of Annotation itself. The definition of the <em><strong>Persistable Annotation</strong></em> is given below,</p>
<p><strong>Persistable.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
	public @interface Persistable
	{
		String fileName();
	}</pre>
<p align="justify">Note that we have specified the target for this Annotation as Field and Local variable meaning that this Annotation can be applicable only to Java Fields and Local variables. Also note how the property <code>fileName</code> for this Annotation is defined. The type (String, in this case) followed by the property name which looks like a method definition fashion.</p>
<p align="justify">Having defined this Annotation, let us see how to apply this Annotation on Java Elements. Consider the following code snippet,</p>
<pre class="brush: java; title: ; notranslate">@Persistable(fileName = &quot;movies.txt&quot;) Movie movie;</pre>
<p align="justify">The above code tells to save all the information about the <code>Movie</code> object to the file called <code>movies.txt</code>. But who will do this operation? We haven&#8217;t defined any code that will do this operation. Generally Annotations are interpreted by Tools and once Tools read these Annotation informations, they will perform the required operation. If we want to give default values to a property, then we should follow the strange syntax.</p>
<p><strong>Persistable.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
	public @interface Persistable
	{
		String fileName() default &quot;defaultMovies.txt&quot;;
	}</pre>
<p align="justify">In this case, if the clients didn&#8217;t supply a value to the <code>fileName</code> property, then the default value <code>defaultMovies.txt</code> is taken. Now let us see the syntax of specifying multiple values to a property. Let us assume that we want to save the status of the object in multiple files in which case we should have declared an array to hold the filenames.</p>
<p><strong>Persistable.java</strong></p>
<pre class="brush: java; title: ; notranslate">@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE})
	public @interface Persistable
	{
		String[] fileNames();
	}
</pre>
<p align="justify">And now Clients can given multiple file entries using the traditional array syntax like this,</p>
<pre class="brush: java; title: ; notranslate">@Persistable(
		fileNames = {
			&quot;movie1.txt&quot;, &quot;movie2.txt&quot;, &quot;movie3.txt&quot;} )
	Movie movie;</pre>
<h2 id="Reflecting the Annotation Information">5) Reflecting the Annotation Information</h2>
<h3>5.1) Introduction</h3>
<p align="justify">In this section, let us see how to query for information related to Annotation types using Reflection. As we all know, <em><strong>Java Reflection API</strong></em> is used to dynamically discover information (meta-data information too) for any type of Java Element like Class, Interface, Field, Method, Constructor etc. From Java 5.0 onwards, the Reflection API has been extended to add support for Annotation types too.</p>
<p align="justify">A new interface called <em><strong>Annotated Element</strong></em> (<code>AnnotationElement</code>) has been added to the <code>java.lang.annotation</code> package. This interface is primarily used to tell that the element in consideration is an Annotation Element which means that all the existing classes/interfaces like <code>java.lang.Package</code>, <code>java.lang.Class</code>, <code>java.lang.reflect.Constructor</code>, <code>java.lang.reflect.Field</code> and <code>java.lang.reflect.Method</code> implement the <code>AnnotationElement</code> interface. Following are the useful methods available in the <code>AnnotationElement</code> interface,</p>
<ul>
<li>Boolean isAnnotationPresent(Class) – This method will return true if the annotation type (which is passed as an argument) is present in the calling element object.</li>
<li>Annotation getAnnotation(Class) – When given an Annotation class on the calling element, gives the corresponding Annotation object.</li>
<li>Annotation[] getAnnotations() – Returns an array of Annotations that are present on the calling object.</li>
</ul>
<h4>5.2) Example Program</h4>
<p align="justify">Let us look into a simple example program that makes use of the new interfaces and the methods to query for Annotation information at run-time. For this example, let us define two Annotation types as follows. One is the <em><strong>Author Annotation</strong></em> and the other is the <em><strong>Version Annotation</strong></em>. This is a very common piece of meta-information that can be given to any Java file (or any other type of file).</p>
<p><strong>Author.java</strong></p>
<pre class="brush: java; title: ; notranslate">package reflections;

	import java.lang.annotation.*;

	@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Author
	{
		String name() default &quot;unknown&quot;;
	}
</pre>
<p align="justify">Note the definition of the Author annotation. This is a single-valued Annotation meaning that this Annotation has a single property called <code>name</code>. Also make a note of the <em><strong>Target Annotation</strong></em>. The presence of Target Annotation tells that Author Annotation can only be applied to Java elements like Constructor, Method and Type (Class/Interface). Another important thing to note is the <em><strong>Retention</strong></em> for this Annotation is set to Run-time because we want this Annotation information to be available to the JVM while the program is running. The <code>name</code> property is also given a default value <code>unknown</code> if the consuming Application fail to provide an explicit value.</p>
<p align="justify">Following is the definition of the <em><strong>Version Annotation</strong></em>. It looks exactly the same as Author Annotation except the fact that it has a property called <code>number</code> (which is of type double) to hold the version value.</p>
<p><strong>Version.java</strong></p>
<pre class="brush: java; title: ; notranslate">package reflections;

	import java.lang.annotation.ElementType;
	import java.lang.annotation.Retention;
	import java.lang.annotation.RetentionPolicy;
	import java.lang.annotation.Target;

	@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.TYPE})
	@Retention(RetentionPolicy.RUNTIME)
	public @interface Version
	{
		double number();
	}</pre>
<p align="justify">Let us have a look at the following class definition that makes use of the above declared Annotations. The Annotations are applied at the class-level as well as in the method-level.</p>
<p><strong>AnnotatedClass.java</strong></p>
<pre class="brush: java; title: ; notranslate">package reflections;

	@Author(name = &quot;Johny&quot;)
	@Version(number = 1.0)
	public class AnnotatedClass
	{
		@Author(name = &quot;Author1&quot;)
		@Version(number = 2.0f)
		public void annotatedMethod1()
		{
		}

		@Author(name = &quot;Author2&quot;)
		@Version(number = 4.0)
		public void annotatedMethod2()
		{
		}
	}</pre>
<p align="justify">This program makes use of the new API to read the Annotation related information that are applied on various Java Elements. The utility method <code>readAnnotation()</code> takes a parameter of type <code>AnnotationElement</code> which can represent a Class, method or Constructor. Then it queries for a list of Annotations of that particular element by calling the <code>getAnnotations()</code> method. Then the array is iterated to get the individual element, then made a downcast to extract the exact information &#8211; <code>Author.name()</code> and <code>Version.number()</code>.</p>
<p><strong>AnnotationReader.java</strong></p>
<pre class="brush: java; title: ; notranslate">package reflections;

	import java.lang.annotation.Annotation;
	import java.lang.reflect.AnnotatedElement;
	import java.lang.reflect.Method;

	public class AnnotationReader
	{
		public static void main(String args[]) throws Exception
		{
			Class&lt;AnnotatedClass&gt; classObject = AnnotatedClass.class;
			readAnnotation(classObject);
			Method method1 = classObject.getMethod(&quot;annotatedMethod1&quot;, new Class[]{});
			readAnnotation(method1);
			Method method2 = classObject.getMethod(&quot;annotatedMethod2&quot;, new Class[]{});
			readAnnotation(method2);
		}

		static void readAnnotation(AnnotatedElement element)
		{
			try
			{
				System.out.println(&quot;\nFinding annotations on &quot; + element.getClass().getName());
				Annotation[] classAnnotations = element.getAnnotations();

				for(Annotation annotation : classAnnotations)
				{
					if (annotation instanceof Author)
					{
						Author author = (Author)annotation;
						System.out.println(&quot;Author name:&quot; + author.name());
					}
					else if (annotation instanceof Version)
					{
						Version version = (Version)annotation;
						System.out.println(&quot;Version number:&quot; + version.number());
					}
				}
			}
			catch (Exception exception)
			{
				exception.printStackTrace();
			}
		}
	}</pre>
<p align="justify">The output for the above program is as follows,</p>
<p>Output</p>
<pre class="brush: java; title: ; notranslate">Finding annotations on java.lang.Class
	Version number:1.0
	Author name:Johny

	Finding annotations on java.lang.reflect.Method
	Author name:Author1
	Version number:2.0

	Finding annotations on java.lang.reflect.Method
	Author name:Author2
	Version number:4.0
</pre>
<h2>6) Conclusion</h2>
<p align="justify">Before the advent of Annotations, Applications had to define their meta-data in some configuration files and usually these meta-data were externalized from the Application. Now, they can directly define this meta-data information in the source code. The concept of Annotating elements in Java is gaining much popurality because of its robustness and simplicity of usage. When effectively applied on Java elements, Annotations can be of great use.</p>
<h2>7) Reference Books</h2>
<p><img class="alignleft" src="http://ecx.images-amazon.com/images/I/41fjX8EYsFL._SL125_.jpg" alt="" width="95" height="125" /></p>
<p>Buy from <a href="http://www.flipkart.com/java-5-0-tiger-0596007388/p/itmczzj4cxnzb2vu?pid=9780596007386&amp;affid=suthukrish" target="_blank">FlipKart.com</a> or <a href="http://astore.amazon.com/javabeat-20/detail/0596007388" target="_blank">Amazon.com</a></p>
<p>The foreword to this new O&#8217;Reilly series explains that a &#8220;Developer&#8217;s Notebook&#8221; is the raw scribbling of an &#8220;Alpha Geek&#8221; as he or she examines some exciting new technology. That pretty much describes &#8220;Java 1.5 Tiger.&#8221; It&#8217;s raw, it&#8217;s scribbling, and it&#8217;s exciting nonetheless.</p>
<p><img class="alignnone alignleft" src="http://ecx.images-amazon.com/images/I/51AG8p4X7WL._SL125_.jpg" alt="" width="94" height="125" /></p>
<p>Buy from <a href="http://www.flipkart.com/java-concurrency-practice-8131713393/p/itmdytstgbfk7g8e?pid=9788131713396&amp;affid=suthukrish" target="_blank">FlipKart.com</a> or <a href="http://astore.amazon.com/javabeat-20/detail/0321349601" target="_blank">Amazon.com</a></p>
<p>Concurrency, in the form of threads, has been present in the Java language from its beginning, and this book is all about concurrency in the current and future versions of Java with an emphasis on writing practical code. This book does for concurrent programming in Java what Geary&#8217;s series of books did for graphical Java &#8211; it moves concurrent Java programming out of the realm of applets containing bouncing balls and into that of providing real solutions for professional programmers. (<a title="Book Review: Java Concurrency in Practice" href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" target="_blank">read our review</a>)</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/08/annotations-in-java-5-0/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
	</channel>
</rss>
