<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>java5 &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/java5/</link>
	<description>Feed of posts on WordPress.com tagged "java5"</description>
	<pubDate>Thu, 03 Dec 2009 06:57:07 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[Criar objeto JSON com XStream]]></title>
<link>http://cadocruz.wordpress.com/2009/07/21/criar-objeto-json-com-xstream/</link>
<pubDate>Tue, 21 Jul 2009 14:28:20 +0000</pubDate>
<dc:creator>cadocruz</dc:creator>
<guid>http://cadocruz.wordpress.com/2009/07/21/criar-objeto-json-com-xstream/</guid>
<description><![CDATA[Para criar um objeto JSON a partir de um objeto java é muito simples com o XStream. Primeiro precisa]]></description>
<content:encoded><![CDATA[Para criar um objeto JSON a partir de um objeto java é muito simples com o XStream. Primeiro precisa]]></content:encoded>
</item>
<item>
<title><![CDATA[Enum in Java 5 - Comparing == or .equals]]></title>
<link>http://bluez25.wordpress.com/2009/07/10/enum-in-java-5-comparing-or-equals/</link>
<pubDate>Fri, 10 Jul 2009 23:04:43 +0000</pubDate>
<dc:creator>Shan Kandaswamy</dc:creator>
<guid>http://bluez25.wordpress.com/2009/07/10/enum-in-java-5-comparing-or-equals/</guid>
<description><![CDATA[Its been a long time since I blogged and decided to start sharing my thoughts and experience on blog]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><span style="font-family:times new roman;">Its been a long time since I blogged and decided to start sharing my thoughts and experience on blogs starting today&#8230;.</span></p>
<p>I had a interesting discussion with one of my developer yesterday and ended up in a heated discussion as in why we should use = = comparison for comparing two ENUM objects vs using .equals method. First of all to give a background on this topic, Java 5 introduced so called ENUM objects which is a very useful type-safety objects we can use in our development to control the values where in old school way we use to have static constants around&#8230;.Read more on this<a href="http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html"> http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html </a></p>
<p>Difference between using == comparison and .equals comparison is that when we use == operator, we are actually comparing and verifying whether the references of the two objects are pointing to the same or not versus using .equals will actually check the value for tell if they are the same objects.</p>
<pre>String str1 = "abc"; String str2 = "def";
if ( (str1 + str2) == "abcdef" )  // Bad way
{    ......}
if ( (str1 + str2).equals("abcdef") ) // Good way
{   .....
}</pre>
<p>Now how is it good to compare Enums using == is same as .equals and what is the preferred way of comparing&#8230;..</p>
<p>Enums are single instance which holds only one value at a time. that being said you can actually check if the references of two enums are pointing to the same which is good&#8230;</p>
<p>In real practice do we aks our developers to use == comparison for enums only since it is ok to d so and use .equals for other object comparison.. I dont agree with that..why confuse people with two different standards&#8230;</p>
<p>I think thats why the author of Enum (Josh Bloch) has thought about the same and has overridden the .equals method and hascode to actually to do the == comparison under the hood so that the developers will get in to standard practice of using .equals for all the objects including Enum objects.</p>
<p>I personally prefer to use .equals for enums also&#8230; pen your thoughts&#8230;..</p>
<p>-Shan</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Free Downloadable Java, J2EE, Struts, Spring, AJAX, JavaScript, CSS, XML EBooks]]></title>
<link>http://javadairy.wordpress.com/2008/08/18/free-downloadable-java-j2ee-struts-spring-ajax-javascript-css-xml-ebooks/</link>
<pubDate>Mon, 18 Aug 2008 16:16:00 +0000</pubDate>
<dc:creator>javadairy</dc:creator>
<guid>http://javadairy.wordpress.com/2008/08/18/free-downloadable-java-j2ee-struts-spring-ajax-javascript-css-xml-ebooks/</guid>
<description><![CDATA[Free Downloadable Java, J2EE, Struts, Spring, AJAX, JavaScript, CSS, XML EBooks]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.books4java.blogspot.com/">Free Downloadable Java, J2EE, Struts, Spring, AJAX, JavaScript, CSS, XML EBooks </a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JBoss guide: How to enable SSL (HTTPS) on JBoss, as well as other "nice-to-know" configurations]]></title>
<link>http://roneiv.wordpress.com/2008/01/03/jboss-tutorial-how-to-enable-ssl-https-on-jboss-as-well-as-other-nice-to-know-configurations/</link>
<pubDate>Thu, 03 Jan 2008 17:42:03 +0000</pubDate>
<dc:creator>roneiv</dc:creator>
<guid>http://roneiv.wordpress.com/2008/01/03/jboss-tutorial-how-to-enable-ssl-https-on-jboss-as-well-as-other-nice-to-know-configurations/</guid>
<description><![CDATA[From time to time you might have the need of running a web application over https, or there can be r]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>From time to time you might have the need of running a web application over https, or there can be requests of having Single-Sign-On between multiple web applications running on your server. This small jboss-guide will give you some clues on how to solve tasks like this, with configurations for both jboss-4.0.4.GA and jboss-4.2.2.GA. Since the name of the server instance might differ and it&#8217;s also possible to use custom names, I&#8217;ll refer to it as jboss/server/&#60;NAME&#62;/, but what I mean here is for example jboss/server/default/.</p>
<h2>Changing the port that jboss runs on</h2>
<p>For 4.0.4 you should locate the <b>server.xml</b> inside jboss/server/&#60;NAME&#62;/deploy/jbossweb-tomcat55.sar/, and then change the port=&#8221;8080&#8243; parameter in the HTTP Connector to your wishes, for example port 80 as I have done it here.</p>
<pre class="brush: xml;">
 &lt;!-- A HTTP/1.1 Connector on port 8080 --&gt;
      &lt;Connector port=&quot;80&quot; address=&quot;${jboss.bind.address}&quot;
         maxThreads=&quot;250&quot; strategy=&quot;ms&quot; maxHttpHeaderSize=&quot;8192&quot;
         emptySessionPath=&quot;true&quot;
         enableLookups=&quot;false&quot; redirectPort=&quot;8443&quot; acceptCount=&quot;100&quot;
         connectionTimeout=&quot;20000&quot; disableUploadTimeout=&quot;true&quot;/&gt;
</pre>
<p>For 4.2.2 you do exactly the same, but the server.xml is located inside jboss/server/&#60;NAME&#62;/deploy/jboss-web.deployer/ instead.</p>
<h2>Make tomcat able to compile java5 &#8211; by default it doesn&#8217;t</h2>
<p>If you have the need of using java5 (jdk 1.5), you need to set the source-level of the compiler. If you don&#8217;t do this and have deployed web-applications with java5 code, you will get exceptions during startup. For 4.0.4 edit the <b>web.xml</b> in jboss/server/&#60;NAME&#62;/deploy/jbossweb-tomcat55.sar/conf. Locate the jsp servlet by searching for &#60;servlet-name&#62;jsp&#60;/servlet-name&#62;, and uncomment the section that enables jdk1.5 features:</p>
<pre class="brush: xml;">
  &lt;!-- Uncomment to use jdk1.5 features in jsp pages --&gt;
      &lt;init-param&gt;
         &lt;param-name&gt;compilerSourceVM&lt;/param-name&gt;
         &lt;param-value&gt;1.5&lt;/param-value&gt;
      &lt;/init-param&gt;
</pre>
<p>For 4.2.2 you find the <b>web.xml</b> inside jboss/server/&#60;NAME&#62;/deploy/jbossweb-deployer/conf. Locate the same servlet, and make sure that the parameters both for source &#38; target compiler are set like this:</p>
<pre class="brush: xml;">
   	&lt;servlet&gt;
        &lt;servlet-name&gt;jsp&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.apache.jasper.servlet.JspServlet&lt;/servlet-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;fork&lt;/param-name&gt;
            &lt;param-value&gt;false&lt;/param-value&gt;
        &lt;/init-param&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;xpoweredBy&lt;/param-name&gt;
            &lt;param-value&gt;false&lt;/param-value&gt;
        &lt;/init-param&gt;
        &lt;init-param&gt;
         &lt;param-name&gt;compilerSourceVM&lt;/param-name&gt;
         &lt;param-value&gt;1.5&lt;/param-value&gt;
        &lt;/init-param&gt;
  	&lt;init-param&gt;
         &lt;param-name&gt;compilerTargetVM&lt;/param-name&gt;
         &lt;param-value&gt;1.5&lt;/param-value&gt;
        &lt;/init-param&gt;</pre>
<h2>Activate support for Single Sign-On</h2>
<p>For both versions, locate <b>server.xml</b> (4.0.4 =  jboss/server/&#60;NAME&#62;/deploy/jbossweb-tomcat55.sar/, 4.2.2 = jboss/server/&#60;NAME&#62;/deploy/jboss-web.deployer/). Find the &#8220;Host&#8221; section, and uncomment the following Valve:</p>
<pre class="brush: xml;">
   	 &lt;!-- Uncomment to enable single sign-on across web apps
                deployed to this host. Does not provide SSO across a cluster.     

                If this valve is used, do not use the JBoss ClusteredSingleSignOn
                valve shown below. 

                A new configuration attribute is available beginning with
                release 4.0.4:

                cookieDomain  configures the domain to which the SSO cookie
                              will be scoped (i.e. the set of hosts to
                              which the cookie will be presented).  By default
                              the cookie is scoped to &quot;/&quot;, meaning the host
                              that presented it.  Set cookieDomain to a
                              wider domain (e.g. &quot;xyz.com&quot;) to allow an SSO
                              to span more than one hostname.
             --&gt;

            &lt;Valve className=&quot;org.apache.catalina.authenticator.SingleSignOn&quot; /&gt;</pre>
<p>Then in your jboss-web.xml it&#8217;s important that all the web applications that are going to &#8220;exchange&#8221; credentials points to the same security-domain:</p>
<pre class="brush: xml;">
&lt;jboss-web&gt;
 	&lt;security-domain&gt;java:/jaas/USE_THE_SAME_APPLICATION_POLICY_HERE&lt;/security-domain&gt;
	&lt;context-root&gt;/YOUR_APPLICATION_ROOT&lt;/context-root&gt;
&lt;/jboss-web&gt;</pre>
<p>If you now open and logon to one application, going to another one running on the same server should not prompt you for username/password again. Note that there are alternatives also if you have applications running on different servers/locations &#8211; check the other Valves.</p>
<h2>Enable SSL on JBoss</h2>
<p>In this example I&#8217;m only using a self-signed certificate, but the procedure would be more or less the same even if you are going to use a certificate from a Certification Authority.</p>
<ol>
<li>Generate the keystore with the following command
<pre class="brush: xml;">
keytool -genkey -alias tomcat -keyalg RSA -keystore NAME_OF_KEYSTORE -validity NUMBER_OF_DAYS</pre>
</li>
<li> Copy the file into the jboss/server/&#60;NAME&#62;/conf/ directory</li>
<li>Edit the <b>server.xml</b> (4.0.4 =  jboss/server/&#60;NAME&#62;/deploy/jbossweb-tomcat55.sar/, 4.2.2 = jboss/server/&#60;NAME&#62;/deploy/jboss-web.deployer/).For 4.0.4 the SSL-connector should be configured like:
<pre class="brush: xml;">
 &lt;!-- SSL/TLS Connector configuration using the admin devl guide keystore     --&gt;
      &lt;Connector port=&quot;THE_PORT_YOU_LIKE&quot; address=&quot;${jboss.bind.address}&quot;
           maxThreads=&quot;100&quot; strategy=&quot;ms&quot; maxHttpHeaderSize=&quot;8192&quot;
           emptySessionPath=&quot;true&quot;
           scheme=&quot;https&quot; secure=&quot;true&quot; clientAuth=&quot;false&quot;
           keystoreFile=&quot;${jboss.server.home.dir}/conf/THE_KEYSTORE_NAME&quot;
           keystorePass=&quot;PASSWORD_FOR_THE_KEYSTORE&quot; sslProtocol = &quot;TLS&quot; /&gt;</pre>
<p>For 4.2.2, configure it like this:</p>
<pre class="brush: xml;">
 &lt;Connector port=&quot;THE_PORT_YOU_LIKE&quot; protocol=&quot;HTTP/1.1&quot; SSLEnabled=&quot;true&quot;
               maxThreads=&quot;150&quot; scheme=&quot;https&quot; secure=&quot;true&quot;
               clientAuth=&quot;false&quot;
	       strategy=&quot;ms&quot;
               address=&quot;${jboss.bind.address}&quot;
               keystoreFile=&quot;${jboss.server.home.dir}/conf/THE_KEYSTORE_NAME&quot;
               keystorePass=&quot;PASSWORD_FOR_THE_KEYSTORE&quot;
               truststoreFile=&quot;${jboss.server.home.dir}/conf/THE_KEYSTORE_NAME&quot;
               truststorePass=&quot;PASSWORD_FOR_THE_KEYSTORE&quot;
               sslProtocol=&quot;TLS&quot;/&gt;</pre>
</li>
<li>Now you should be able to access your application through https. Remember to use https:// instead of http:// in your browser-url, or else it will fail.</li>
<li>Remember that if you want to disable the non-secured port 8080 (or custom), making sure that people can only access through https, comment and disable that connector in the same server.xml.</li>
</ol>
<h2>Tell jboss 4.2.2 to not use the bundled JSF 1.2 implementation</h2>
<p>By default this version of jboss comes bundled with the Glassfish JSF 1.2 implementation. If you deploy web applications that use other implementations, like myfaces, you should tell jboss to use the implementations(s) deployed together with the web applications instead. Do this by adding the following to the web.xml of your application(s):</p>
<pre class="brush: xml;">
  &lt;context-param&gt;
     &lt;param-name&gt;org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL&lt;/param-name&gt;
     &lt;param-value&gt;true&lt;/param-value&gt;
  &lt;/context-param&gt;</pre>
<h2>Access jboss-4.2.2GA using ip address instead of localhost &#8211; use the &#8220;-b&#8221; parameter</h2>
<p>I&#8217;ve been using the 4.0.4 version for some time, and I could start it on my machine (accessing it through localhost:8080), and access it from other machines in my network it by using the ip-address of my machine instead of localhost. With 4.2.2, you can start it the same way and it will work from your machine by going localhost. But trying to start the application remotely from other machines by using the ip-address would fail, giving you a 404.</p>
<p>This is because before 4.2.2.GA, jboss was always bound to the any address &#8220;0.0.0.0&#8243;. But this was considered a security issue, and this default behavior was removed.  It&#8217;s now up to the user to explicitly configure this.</p>
<p>What you need to do to solve it is to start the jboss with another parameter, you need to set the bind address for the jboss services. The following command would start a jboss server named &#8220;myserver&#8221; on ip 192.168.100.100:</p>
<pre class="brush: xml;">
  run.bat -c myserver -b 192.168.100.100</pre>
<p>If you now try to start the application from other machines by using this IP it works! If you use the server named default  you can leave out the -c parameter. It&#8217;s also possible to revert back to the &#8220;old configuration&#8221; by using -b 0.0.0.0, but this is not recommended.Ok, I hope that this small guide might be of help to someone! <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Usage of new Java5 method - inheritedChannel()]]></title>
<link>http://rskommu.wordpress.com/2007/12/28/usage-of-new-java5-method-inheritedchannel/</link>
<pubDate>Fri, 28 Dec 2007 17:21:16 +0000</pubDate>
<dc:creator>Rajs</dc:creator>
<guid>http://rskommu.wordpress.com/2007/12/28/usage-of-new-java5-method-inheritedchannel/</guid>
<description><![CDATA[Posted in blog city on September 3rd 2004   I am struggling to understand how to use the new method ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><em>Posted in blog city on September 3rd 2004</em>  </p>
<p>I am struggling to understand how to use the new method <a target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#inheritedChannel()"><font face="courier new,courier,monospace">inheritedChannel</font></a><font face="courier new,courier,monospace">()</font> in <a target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html"><font face="courier new,courier,monospace">java.lang.System</font></a>.<br />
Any example code on the usage? The method returns an instance of <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/Channel.html"><font face="courier new,courier,monospace">Channel</font></a> interface which has only two methods close() and isOpen(). So, unless one knows the exact class that is returned by this method (<a target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/SocketChannel.html"><font face="courier new,courier,monospace">SocketChannel</font></a>, <font face="courier new,courier,monospace"><a target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/DatagramChannel.html">DatagramChannel</a></font>, <font face="courier new,courier,monospace"><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/channels/ServerSocketChannel.html">ServerSocketChannel</a></font> etc), there is nothing much that can be done with <font face="courier new,courier,monospace">inheritedChannel</font> method.</p>
<p>So, are developers expected to somehow &#8220;detect&#8221; (<font face="courier new,courier,monospace">instanceof</font>?) the exact class that is being returned and use this method? If that is indeed the intention, not sure what is the purpose of returning an interface that is useless.</p>
<p> <em>Comments</em></p>
<table border="0" width="97%" cellPadding="0" cellSpacing="0">
<tr class="rowhighlight">
<td width="1%" align="right" noWrap="true" vAlign="top" style="padding-left:0;">
<div style="margin:3px;"><strong>#1</strong></div>
</td>
<td>
<div style="margin:3px;">&#8216;<strong></strong>&#8216; posted this on Sat 4 Sep 2004, 12:37 am</p>
<div style="margin:10px;"><img src="http://rajs.blog-city.com/images/noprofile.jpg" style="float:right;margin-bottom:8px;margin-left:10px;width:32px;height:32px;background-color:white;border:black 1px solid;" />What would be the point of giving it a less specific return type? It gives the programmer a good idea about what is going on. Most types do not specialise Channel.The idea, I believe, is that a program would be written to expect the inherited channel to be something specific. Obviously giving a nice error message in the case of that expectation not being reached is a good idea. So a logind style program may start up a Java program as a particular user inheritting a SocketChannel. Listening to ports less than 1024 is not allowed for user programs under UNIX, therefore a web server may inherit a ServerSocketChannel bound to port 80. It&#8217;s tough if you want two channels, for instance to support both HTTP and HTTPS.</p>
<p><a target="_blank" href="http://jroller.com/page/tackline/">Tom Hawtin [tackline@claranet.com]</a></div>
</div>
</td>
</tr>
<tr>
<td width="1%" align="right" noWrap="true" vAlign="top" style="padding-left:0;">
<div style="margin:3px;"><strong>#2</strong></div>
</td>
<td>
<div style="margin:3px;">&#8216;<strong><a href="http://rajs.blog-city.com/console/profile/popup/?i=14982" title="view profile">Rajs</a></strong>&#8216; posted this on Thu 9 Sep 2004, 4:06 pm</p>
<div style="margin:10px;"><img src="http://rajs.blog-city.com/images/noprofile.jpg" style="float:right;margin-bottom:8px;margin-left:10px;width:32px;height:32px;background-color:white;border:black 1px solid;" />To me looks like this is violating some fundamental principles of OO. The API is kind of forcing it&#8217;s users to always check for the return type. With out this one cannot do anything. It is kind of same as returning java.lang.Object.<br />
Ideally it would have better if there is some other interface or base class from which all these different channels are derived OR there should have been more methods that Channel interface must be enforcing. To me, it looks like a design issue.</div>
</div>
</td>
</tr>
<tr>
<td width="1%" align="right" noWrap="true" vAlign="top" style="padding-left:0;">
<div style="margin:3px;"><strong>#4</strong></div>
</td>
<td>
<div style="margin:3px;">&#8216;<strong><a href="http://rajs.blog-city.com/console/profile/popup/?i=14982" title="view profile">Rajs</a></strong>&#8216; posted this on Mon 4 Oct 2004, 2:50 am</p>
<div style="margin:10px;"><img src="http://rajs.blog-city.com/images/noprofile.jpg" style="float:right;margin-bottom:8px;margin-left:10px;width:32px;height:32px;background-color:white;border:black 1px solid;" />Anon,<br />
I am aware of the SelectorProvider api when I wrote this blog. That&#8217;s exactly the problem I was talking about. One has to do an &#8220;instance of&#8221; kind of operation to figure out which among the ServerSocketChannel, SocketChannel and DatagramChannel is returned. There is no other way to figure out.Rajs</div>
</div>
</td>
</tr>
</table>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Bnd is now Java5 aware]]></title>
<link>http://cdivilly.wordpress.com/2007/08/29/bnd-is-now-java5-aware/</link>
<pubDate>Wed, 29 Aug 2007 11:20:40 +0000</pubDate>
<dc:creator>cdivilly</dc:creator>
<guid>http://cdivilly.wordpress.com/2007/08/29/bnd-is-now-java5-aware/</guid>
<description><![CDATA[Update: Turns out not long after I wrote this, Bnd did gain awareness of Java 5 constructs. I found ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Update:</strong> Turns out not long after I wrote this, <a href="http://www.aqute.biz/Code/Bnd">Bnd</a> did gain awareness of Java 5 constructs. I found this out recently when rebuilding some code for the first time since late 2007. <a href="http://maven.apache.org/">Maven</a> as it is wont, updated its plugins to the latest versions, including the <a title="maven-bundle-plugin" href="http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html">maven-bundle-plugin</a> (which uses Bnd) and code which has not been changed in over a year suddenly stopped building. The Culprit? Undeclared dependencies on annotations, which previously went unnoticed by Bnd, were now being spotted by Bnd and duely reported as errors.</p>
<p><span style="text-decoration:line-through;">Peter Krien&#8217;s <a title="Bnd" href="http://www.aqute.biz/Code/Bnd">Bnd</a> utility is a nice piece of work, one feature is that it can pretty accurately compute the correct set of packages for the Import-Package directive of a bundle. Just be aware that it is designed for Java 1.4 and earlier and therefore does not examine new language constructs introduced in Java5 such as annotations and static imports.</span></p>
<p><span style="text-decoration:line-through;">If you forget this then you won&#8217;t see any problems until run-time (in the case of annotations with run-time retention), at the time when whatever introspection code consumes your annotated classes. Since the packages where the annotations were declared were omitted from the Import-Package declaration they will not be visible in the bundle&#8217;s class loading scope. Rather than failing to load the annotated class the JVM will instantiate the class as normal, but omit the annotation reflection data, i.e. Class.getAnnotation() will return null.</span></p>
<p><span style="text-decoration:line-through;">The solution is of course to add the packages where the missing annotations are declared to the Import-Package directive, you need to use an explicit package name, a wild-card pattern will not suffice (since Bnd attempts to refine all wild card patterns down to the subset of actual uses).I generally use a statement something like:</span></p>
<p><span style="text-decoration:line-through;">Import-Package: com.foo.annotations.pkg, *</span></p>
<p><span style="text-decoration:line-through;">This makes Bnd add the explicit import for the missing annotation package and leaves it to compute all other imports for you</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Improper use of Generics could breach type safety]]></title>
<link>http://deepjava.wordpress.com/2007/03/20/improper-use-of-generics-could-breach-type-safety/</link>
<pubDate>Tue, 20 Mar 2007 02:31:51 +0000</pubDate>
<dc:creator>Deepak Anupalli</dc:creator>
<guid>http://deepjava.wordpress.com/2007/03/20/improper-use-of-generics-could-breach-type-safety/</guid>
<description><![CDATA[I was going through Java discussion forums and happened to come across an interesting discussion rel]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I was going through Java discussion forums and happened to come across an interesting discussion related to Generics. It was about a loop hole in the Java Generics feature that allows a method to throw a Checked Exception without declaring it in the throws clause.</p>
<p>This is definitely going to be freaky and I wouldn&#8217;t encourage you to take advantage of this in your development. Initially I thought this could be a loop hole in the Compiler implementation, but later realized that the behavior is inherent with the Generics design.</p>
<pre>
<span class="Modifier">public</span> <span class="Type">class</span> RethrowCheckedException {
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> rethrow(Throwable t) {//No throws clause
        RethrowCheckedException.&#60;RuntimeException&#62;throwing(t);
    }

    <span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T extends Throwable&#62; <span class="Type">void</span> throwing(Throwable t) throws T {
        <span class="Statement">throw</span> (T)t;
    }
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> main(String[] args) {
        <span class="Statement">try</span> {
            <span class="Statement">throw</span> <span class="Keyword">new</span> Exception("dummy");
        } <span class="Statement">catch</span> (Exception e) {
            rethrow(e);
        }
    }
}</pre>
<p>Using the <span style="font-style:italic;">rethrow()</span> method we can make java.lang.Exception to escape from <span style="font-style:italic;">main()</span> without declaring it in its throws clause. The type &#60;RuntimeException&#62; specified while invoking the <span style="font-style:italic;">throwing()</span> method is know as &#8220;explicit type argument&#8221;. (which is complementary to the type inference discussed below)</p>
<p><span style="font-size:1.2em;">Type Inference</span></p>
<p>To understand how the above thing works, we need to get an idea about type inference and explicit typing. Take a look at the the following example</p>
<pre>
<span class="Modifier">public</span> <span class="Type">class</span> ArrayStore {
    <span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T&#62; <span class="Type">void</span> store(T[] array, T item) {
        <span class="Statement">if</span> (array.length &#62; 0)
            array[0] = item;
    }
    <span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> main(String[] args) {
        store(<span class="Keyword">new</span> String[1], <span class="String">"abc"</span>); <span class="InlineComment">//ok</span>
        store(<span class="Keyword">new</span> String[1], <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//??</span>
    }
}</pre>
<p>Surprisingly, both the <span style="font-style:italic;">store</span> method invocations shown, compile. Compiler infers T to String for the first <span style="font-style:italic;">store()</span> invocation as both the arguments are Strings, this process is known as &#8220;type inference&#8221;. We expect the second one to fail as T cannot be evaluated to both a String as well as an Integer. But, the Compiler infers T to a common super class or interface other than java.lang.Object. As String and Integer have Serializable and Comparable as super interfaces, Compiler deduces T to be a Serializable or Comparable and allows compilation. The result of which is an ArrayStoreException at runtime, defying the whole point of Generics and type safety.</p>
<p>How do we resolve this problem? We can use the &#8220;explicit type argument&#8221; in such cases.</p>
<pre></pre>
<pre>ArrayStore.&#60;String&#62;store(<span class="Keyword">new</span> String[1], <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//compilation Error</span></pre>
<p>Explicitly specifying the type argument as String, forces the compiler to evaluate T to String (overriding the compiler&#8217;s type inference mechanism) and hence compilation fails.</p>
<p>Now that we got a hang on type inference, we&#8217;ll get back to the loop hole.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T extends Throwable&#62; <span class="Type">void</span> throwing(Throwable t) throws T {
    <span class="Statement">throw</span> (T)t;
}</pre>
<p>The <span style="font-style:italic;">throwing()</span> method defines type &#60;T extends Throwable&#62; which is declared in its throws clause and is no way related to the argument passed. The <span style="font-style:italic;">rethrow()</span> method explicitly specifies the type as RuntimeException, making the method signature of the <span style="font-style:italic;">throwing()</span> method to appear as shown below, at compile time.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> throwing(Throwable t) throws RuntimeException {
    <span class="Statement">throw</span> (RuntimeException)t;
}</pre>
<p>Compiler evaluates the method signature by replacing the type variable T with its inferred or explicitly specified type, which is RuntimeException in our case. As a result of this Compiler doesn&#8217;t enforce exception handling or re-throwing it in the <span style="font-style:italic;">rethrow()</span> method. After compilation and type erasure, all the generic type information is erased as shown below.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> <span class="Type">void</span> throwing(Throwable t) throws Throwable {
    <span class="Statement">throw</span> (Throwable)t;
}</pre>
<p><span style="font-size:1.2em;">Some thoughts</span><br />
Type inference or explicit type argument could do some damage when the Generic type information is not captured properly. In the loop hole case, since the exception argument passed to the <span style="font-style:italic;">throwing()</span> method is not related to the Generic type (T), compiler was blind folded. If we modify the method signature as shown below, method invocation fails to compile.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T extends Throwable&#62; <span class="Type">void</span> throwing(T t) throws T {
    <span class="Statement">throw</span> (T)t;
}</pre>
<p>Similarly, in the ArrayStore example we cannot expect the programmer to invoke the store method by explicitly specifying the type everytime at the calling context. A better way of capturing the generic type information in this case is to establish a relationship between Type variables(T&#8217;s), to enforce expected compile time checks.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T, S extends T&#62; <span class="Type">void</span> store(T[] array, S item) { ... }</pre>
<p>And interestingly, the following generic type declarations work as expected unlike the ArrayStore example.</p>
<pre>
<span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T&#62; setMap(Map&#60;T, T&#62; map) { ... }
<span class="Modifier">public</span> <span class="Modifier">static</span> &#60;T&#62; addToList(List&#60;T&#62; list, T element) { ...}</pre>
<pre>
addToList(<span class="Keyword">new</span> ArrayList&#60;String&#62;(), <span class="Keyword">new</span> Integer(10)); <span class="InlineComment">//fails to compile</span></pre>
<p>Java Language Specification(JLS) 3.0, 15.12.2.7 states &#8220;The process of type inference is inherently complex.&#8221;</p>
<p>Yes indeed it is really complex to understand type inference. All this appeals for better understanding of the type inference mechanism and how it applies. Probably you can get more information from <a href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Argument%20Inference" title="FAQ by Angelika Langer">FAQ by Angelika Langer</a>.</p>
<p class="zoundry_bw_tags">   <!-- Tag links generated by Zoundry Blog Writer. Do not manually edit. http://www.zoundry.com --><br />
<span class="ztags"><span class="ztagspace">Technorati</span> : <a href="http://technorati.com/tag/deepjava" class="ztag" rel="tag">deepjava</a>, <a href="http://technorati.com/tag/java" class="ztag" rel="tag">java</a>, <a href="http://technorati.com/tag/java5" class="ztag" rel="tag">java5</a></span><br />
<span class="ztags"><span class="ztagspace">Del.icio.us</span> : <a href="http://del.icio.us/tag/java" class="ztag" rel="tag">java</a>, <a href="http://del.icio.us/tag/java5" class="ztag" rel="tag">java5</a></span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Understanding Generics with Collections]]></title>
<link>http://deepjava.wordpress.com/2006/12/22/understanding-generics-with-collections-2/</link>
<pubDate>Fri, 22 Dec 2006 06:09:06 +0000</pubDate>
<dc:creator>Deepak Anupalli</dc:creator>
<guid>http://deepjava.wordpress.com/2006/12/22/understanding-generics-with-collections-2/</guid>
<description><![CDATA[In Java (prior to 5.0), a lot of times you are compelled to downcast your object to a more specific ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In Java (prior to 5.0), a lot of times you are compelled to downcast your object to a more specific one. For example, when you add a String to a List, and when you want to retrieve your String back then you need to downcast.</p>
<pre><span style="font-family:'Courier New';">List myList = <span class="Keyword">new</span> ArrayList();
myList.add(<span class="String">"abc"</span>);
String str = (String)myList.get(0);  

</span></pre>
<p>Downcast is inevitable. Moreover, adding objects of any type to the list is allowed and the developer is responsible to remember the type of each object and perform the appropriate downcast while retrieving them. This gives a way to the type safety problems in Java, as every downcast in the code is a potential case for the wicked ClassCastException. Generics have been introduced to rescue us from these situations, they let you mark the collection to contain elements of a particular data type only, say a List of Strings. The syntax to specify a List of Strings would look like this. (Note: &#8216;type&#8217; refers to any class definition in Java, e.g. String, Integer, Collection, MyClass etc. are all denoted as types.)</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&#60;String&#62; myList = <span class="Keyword">new</span> ArrayList&#60;String&#62;();
myList.add(<span class="String">"abc"</span>);
String str = myList.get(0);
</span></pre>
<p>The syntax is fairly simple, you need to specify the &#8216;type&#8217; of the Collection in the angular brackets following the Collection type. Such types are known as Generic types or Parameterized types. We&#8217;ll get to know more about defining collection types and substitution in the following sections.</p>
<p>With the above syntax, it is not allowed to add objects or retrieve objects of any other type other than String to the above List and doing that would result in a compile-time error. This is much better than the ClassCastException at runtime, and would definitely save a lot of your development time, isn&#8217;t it? And more importantly the downcast should be made extinct now, as the type of the elements within the collection is explicity informed to the compiler through the Generic syntax.</p>
<p><span style="font-size:1.2em;">Purpose of Generics</span><br />
Generics make your program well formed enabling the compiler to perform enough type checks based on the static type information provided and avoids unexpected type errors that could occur at runtime. Let us get into more practical matters.</p>
<p><span style="font-size:1.2em;">Collections and Substitution rules</span><br />
Collections are the primary motivation for Generics in Java.</p>
<p>Let us take a look at some substitution rules. The following are some legal assignments:</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&#60;Integer&#62; li = <span class="Keyword">new</span> ArrayList&#60;Integer&#62;();
Collection&#60;Integer&#62; ci = <span class="Keyword">new</span> LinkedList&#60;Integer&#62;();
Collection&#60;Integer&#62; cs = <span class="Keyword">new</span> HashSet&#60;Integer&#62;();
List lst = <span class="Keyword">new</span> ArrayList&#60;Number&#62;();
List&#60;Integer&#62; li = <span class="Keyword">new</span> ArrayList();<span class="InlineComment">//warning</span>  

</span></pre>
<p>Here is the substitution principle for collections, (Rule 1) RHS of the assignment should contain a Collection implementation compatible with that of LHS and generified with the same type as that of LHS. The last assignment two assignments are valid, these are allowed to provide compatibility of non-generic (prior to Java 5) code with the new generic approach and vice versa. But, if you compile your code with -Xlint:unchecked option, the last assignment results in a unchecked conversion warning. (Rule 2) Do not ignore such compilation warnings, as they indicate your code to be unsafe (could break at runtime with ClassCastExceptions).</p>
<pre><span style="font-family:'Courier New',courier,monospace;">List&#60;String&#62; ls = <span class="Keyword">new</span> ArrayList&#60;String&#62;();<span class="InlineComment">//1 </span>
ls.add(<span class="String">"abc"</span>);<span class="InlineComment">//2 </span>
ls.add(<span class="String">"xyz"</span>);<span class="InlineComment">//3 </span>
Iterator its = ls.listIterator();<span class="InlineComment">//4 </span>
<span class="Statement">while</span>(its.next()) {<span class="InlineComment">//5 </span>
    String s = its.next();<span class="InlineComment">//6 </span>
    System.out.println(<span class="String">"Element: "</span>+s);
}  

</span></pre>
<p>Does this compile? No, Iterator is not a generic type and hence the assignment of iterator&#8217;s element to the String &#8217;s&#8217; (line 6) fails with a compilation error. Basically, in line 4 we lost the type information while obtaining the iterator and so we need an explicit cast here. Hence, you need to make the Iterator parameterized with String type to avoid the explicit cast.</p>
<pre><span style="font-family:'Courier New',courier,monospace;">Iterator&#60;String&#62; its = ls.listIterator();<span class="InlineComment">//4</span>  

</span></pre>
<p>(Rule 3) When you get an iterator, keySet, entrySet or values from a collection, assign to an appropriate parameterized type as shown above. This is because, these methods are modified to return their corresponding generic types to benifit no-cast code. Most of the Java 5 aware IDEs can do this job for you automatically, rely on them.</p>
<p>The following assignments are invalid:</p>
<pre><span style="font-family:'Courier New',courier,monospace;">Set&#60;String&#62; ss = <span class="Keyword">new</span> HashSet&#60;Integer&#62;();<span class="InlineComment">//Incompatible Types</span>
List&#60;Object&#62; lo = <span class="Keyword">new</span> ArrayList&#60;String&#62;();<span class="InlineComment">//compile-time error</span>  

</span></pre>
<p>Though String is a subtype of Object, the second assignment is not allowed. Collection of Objects is a bigger set comprising of elements of various types (Strings, Integers, Cats, Dogs etc.), but a Collection of Strings strictly contains Strings and both of these cannot be equated (Rule 4). In programmatic sense if this were allowed, we would end up adding objects of any type to a List of Strings, defying the purpose of generics and hence this is not allowed.</p>
<p>Well, with the above restriction, how would you implement a method that accepts a collection of any type, iterate over it and print the elements? For such purposes, Wildcards are introduced for generic types to represent unknown collections.</p>
<p><span style="font-size:1.2em;">Wildcards</span><br />
We know that Object[] is the supertype of all arrays, similarly Collection&#60;?&#62; is the supertype of all generic collections which is pronounced as &#8220;Collection of unknown&#8221;. (Note: Collection&#60;?&#62; represents List&#60;?&#62;, ArrayList&#60;?&#62;, HashSet&#60;?&#62; etc. And Collection&#60;?&#62; is only a reference type and you cannot instantiate it, i.e. new ArrayList&#60;?&#62;() or new HashSet&#60;?&#62;() is not allowed.) (Rule 5) Collections parameterized with wildcards cannot be instantiated.</p>
<p>Using Collection&#60;?&#62; we can implement the iterate and print method as shown below.</p>
<pre><span style="font-family:'Courier New',courier,monospace;"><span class="Modifier">public</span> <span class="Type">void</span> printElements(Collection&#60;?&#62; c) {
    <span class="Statement">for</span>(Object o : c) {
        System.out.println(o);
    }
}
...
List&#60;String&#62; ls = <span class="Keyword">new</span> ArrayList&#60;String&#62;();
List&#60;Cat&#62; lc = <span class="Keyword">new</span> ArrayList&#60;Cat&#62;();
...
printElements(ls);
printElements(lc);</span></pre>
<p>Is Collection&#60;?&#62; same as plain old Collection? No, there are lot of differences between the plain old Collection, Collection&#60;?&#62; and Collection&#60;Object&#62;.</p>
<p>The following are the differences between them:</p>
<ul>
<li>Collection&#60;?&#62; is a homogenous collection that represents a family of generic instantiations of Collection (i.e. Collection&#60;String&#62;, Collection&#60;Integer&#62; etc.)</li>
<li>Collection&#60;Object&#62; is a heterogenous collection or a mixed bag that contains elements of all types, close to the plain old Collection but not same</li>
<li>Collection&#60;?&#62; ensures that you don&#8217;t add aribtrary objects, as we do not know the type of the collection (Rule 6)</li>
<li>Collection&#60;?&#62; cannot be treated as a read-only collection, as it allows remove() and clear() operations</li>
<li>You can assign Collection&#60;String&#62; or Collection&#60;Number&#62; to a Collection&#60;?&#62; reference type, but not to a Collection&#60;Object&#62; (Refer to Rule 4)</li>
</ul>
<pre><span style="font-family:'Courier New',courier,monospace;">List&#60;String&#62; list = <span class="Keyword">new</span> ArrayList&#60;String&#62;();
list.add(<span class="String">"Tiger"</span>);
list.add(<span class="String">"Mustang"</span>);
Collection&#60;?&#62; c = list;
Object o = c.get(0); <span class="InlineComment">//returns "Tiger" downcasted to Object</span>
c.contains(<span class="String">"Tiger"</span>); <span class="InlineComment">//returns true</span>
Iterator itr = c.iterator();
<span class="Statement">while</span>(itr.hasNext()) {
    Object o = itr.next();
    System.out.println(o);
}
c.remove(<span class="String">"Mustang"</span>); <span class="InlineComment">//removes "Mustang" from the List</span>
c.add(<span class="String">"Dolphin"</span>); <span class="InlineComment">//compile-time error (as per Rule 6)</span></span></pre>
<p>Collection&#60;?&#62; appears very restrictive as you do not known the type information. When you obtain your elements from this collection you need to work with objects and would sometimes end up in explicit cast. So, strictly encourage Collection&#60;?&#62; when you need no type specific operations (Rule 7). But, there would be very few such use-cases in practice, where as more frequently you may need to perform operations on a base interface and you do not bother about the implementation type. In such cases you can benifit with the &#8216;bounded wildcards&#8217;.</p>
<p><span style="font-size:1.2em;">Bounded wildcards</span><br />
List&#60;? extends Number&#62; is an example of a bounded wildcard. This represents a homogenous List that contains elements that are subtypes of Number. Bounded wildcards only indicate an unknown type which is a subtype of Number.</p>
<pre><span style="font-family:'Courier New',courier,monospace;"><span class="Modifier">public</span> <span class="Type">void</span> addInteger(List&#60;? extends Number&#62; lnum) {
    Number num = lnum.get(0);
    <span class="Type">byte</span> b = num.byteValue();
    lnum.add(<span class="Keyword">new</span> Integer(10));<span class="InlineComment">//not allowed, compile-time error</span>
}</span></pre>
<p>So, we can obtain elements from the collection assuming the type to be a Number. But, you are not allowed to add anything to the collection as we do not know which subtype of Number the collection contains.</p>
<p>Differences between List&#60;Number&#62; and List&#60;? extends Number&#62;:</p>
<ul>
<li>List&#60;Number&#62; is a heterogenous collection of Number objects (i.e. it can contain instances of Integer, Float, Long, etc.)</li>
<li>List&#60;? extends Number&#62; represents a homogenous collection of Number or its subtypes. It is instantiated with any of List&#60;Integer&#62;, List&#60;Float&#62; etc.</li>
</ul>
<p>&#8220;? extends Type&#8221; is known as the upper bound, and we also have &#8220;? super Type&#8221; which is the lower bound where the unknown type denotes a super type of the specified Type. This is rarely useful with collections but could come handy when we define our own generic types.</p>
<p>We&#8217;ll see more about defining generic types, generic methods and type erasure semantics in my next posts.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Bootstrapping static fields within enums]]></title>
<link>http://deepjava.wordpress.com/2006/12/08/bootstrapping-static-fields-within-enums/</link>
<pubDate>Fri, 08 Dec 2006 14:51:54 +0000</pubDate>
<dc:creator>Deepak Anupalli</dc:creator>
<guid>http://deepjava.wordpress.com/2006/12/08/bootstrapping-static-fields-within-enums/</guid>
<description><![CDATA[In my earlier post on enums in Java 5, we have seen that static fields cannot be accessed within the]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">In my earlier post on <a href="http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50" title="Enums">enums</a> in Java 5, we have seen that static fields cannot be accessed within the enum constructor. With this restriction we could run into few initialization problems discussed below.</span></p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">The other day Rajiv found it difficult to initialize a static cache during enum bootstrap. The following is his enum:</span></p>
<p><pre>
<span class="Modifier">public</span> <span class="Type">enum</span> Tag {
    KEYWORDS(2, 25, <span class="Keyword">true</span>),
    DATE_CREATED(2, 55, <span class="Keyword">false</span>),
    HEADLINE(2, 105, <span class="Keyword">false</span>),
    …
    <span class="Modifier">private</span> <span class="Type">int</span> recordNo;
    <span class="Modifier">private</span> <span class="Type">int</span> datasetNo;
    <span class="Modifier">private</span> <span class="Type">int</span> isRepeat;

    <span class="Modifier">private</span> Tag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo, <span class="Type">int</span> isRepeat) {
        <span class="Keyword">this</span>.recordNo = recordNo;
        <span class="Keyword">this</span>.datasetNo = datasetNo;
        <span class="Keyword">this</span>.isRepeat = isRepeat;
    }
    …
    <span class="Modifier">public</span> <span class="Modifier">static</span> Tag getTag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo) {
        <span class="Statement">for</span>(Tag tag : Tag.values()) { <span class="InlineComment">//$REVIEW$ optimize</span>
            <span class="Statement">if</span>(tag.getRecordNo() == recordNo &#38;&#38; tag.getDatasetNo() == datasetNo){
                <span class="Statement">return</span> tag;
            }
        }
    }
}</pre>
</p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">Rajiv says, &#8220;Deeps, check my implementation of getTag(int recordNo, int datasetNo). I would have liked to make a static map of (recordNo&#60;&#60;8 + datasetNo) vs Tag to make this method fast. Unfortunately, I cannot access that static map from the constructor.&#8221;</span></p>
<p style="margin:7.5pt 3.75pt;"><span style="font-size:10.5pt;font-family:'Trebuchet MS';">So, he would like to have a static cache of enums for easy retrieval based on their properties. But, the concern is where do we initialize this cache/map? In the discussion following the earlier <a href="http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50/">post</a>, we discussed that &#8220;enums are initialized before any static initializers are run&#8221;. Bang! We can initialize this cache in a static block as shown below (actually derived from Neal Gafter&#8217;s discussion on forum).</span></p>
<p><pre>
<span class="Modifier">public</span> <span class="Type">enum</span> Tag {
    KEYWORDS(2, 25, <span class="Keyword">true</span>),
    DATE_CREATED(2, 55, <span class="Keyword">false</span>),
    HEADLINE(2, 105, <span class="Keyword">false</span>),
    …
    <span class="Modifier">private</span> <span class="Modifier">static</span> Map&#60;Integer, Tag&#62; cache;
    <span class="Modifier">static</span> {
        cache = <span class="Keyword">new</span> HashMap&#60;Integer, Tag&#62;();
        <span class="Statement">for</span>(Tag tag : values()) {
            <span class="Type">int</span> key = tag.getRecordNo()&#60;&#60;8 + tag.getDatasetNo();
            cache.put(key, tag);
        }
    }
    …
    <span class="Modifier">public</span> <span class="Modifier">static</span> Tag getTag(<span class="Type">int</span> recordNo, <span class="Type">int</span> datasetNo) {
        <span class="Type">int</span> key = recordNo&#60;&#60;8 + datasetNo;
        <span class="Statement">return</span> cache.get(key);
    }
}</pre>
</p>
<p><span style="font-size:10.5pt;font-family:'Trebuchet MS';">Enum constants are already constructed, by the time static block initializer is run. This is a ridiculous pattern to follow though, when you need to boot strap your static fields within enums.</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Type Safe Enumerations in Java 5.0]]></title>
<link>http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50/</link>
<pubDate>Tue, 21 Nov 2006 17:12:33 +0000</pubDate>
<dc:creator>Deepak Anupalli</dc:creator>
<guid>http://deepjava.wordpress.com/2006/11/21/type-safe-enumerations-in-java-50/</guid>
<description><![CDATA[The new enum construct in Java 5.0 is used to define enumerations. Enumerations are not new to progr]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>The new enum construct in Java 5.0 is used to define enumerations. Enumerations are not new to programming langugages, they existed in C, C++, SmallTalk etc. In Java 5.0 they had to be introduced to overcome safety and ease of use concerns in using the earlier enumeration approaches. Let us take a look at how we used to define enumeration constants prior to Java 5.0.
<p><font size="3">Type Safety concern for enumerations</font><br />In programming sense, enumerations can be treated as just a sequence of integers. Let us define an enumeration that represents a sample of Colors (RED, BLUE, YELLOW, GREEN, ORANGE &#38; PURPLE).</p>
<p><font face="Courier New">public interface Colors {<br />&#160;&#160;&#160; final int RED=1, BLUE=2,&#160;</font><font face="Courier New">YELLOW=3, GREEN=4, ORANGE=5, PURPLE=6;<br />}<br />public interface Shape {<br />&#160;&#160;&#160; void applyColor(int color);<br />&#160;&#160;&#160; &#8230;<br />}<br />Shape box = new Rectangle();//Rectangle implements Shape<br />box.applyColor(Colors.RED);</font></p>
<p><font color="#777777"></font>
<p>Whereever we need a color, we use the constants defined in Colors. But, what if an integer that is not defined for any of the constants is passed to the applyColor() method? Say <font face="Courier New">box.applyColor(8)</font>, It fails. <font face="Courier New">Shape.applyColor()</font> method takes any integer, there is no &#8220;Type Safety&#8221;.</p>
<p>So, it is not true to say enumerations are a sequence of integers. Enumerations should be treated as a separate type. Let us re-define the enumeration to take care of Type Safety.</p>
<p><font size="3">Enumerated Pattern before Java 5<br />
<h2></h2>
<p></font>Prior to Java 5 release, enumerations were defined using the Enumerated pattern described in the book, Effective Java. Enumerated pattern takes care of type safety.<br /> 
</p>
<p><font face="Courier New"></font></p>
<p><font face="Courier New">public final class Color<br />{<br />&#160;&#160;&#160; public static final Color RED = new Color(1);<br />&#160;&#160;&#160; public static final Color BLUE = new Color(2);<br />&#160;&#160;&#160; private int color;</font>
<p><font face="Courier New">&#160;&#160;&#160; //ensures singleton and no instantiations<br />&#160;&#160;&#160; private Color(int color) { this.color = color; } <br />&#160;&#160;&#160; public int getColor() { return color; }<br />&#160;&#160;&#160; //overridden to give meaningful values<br />&#160;&#160;&#160; public String toString() {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; switch (getColor()) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; case 1: return &#8220;RED&#8221; break;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#8230;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; }<br />&#160;&#160;&#160; } </font>
<p><font face="Courier New">&#160;&#160;&#160; public boolean equals(Object obj) { return this == obj;}<br />}</font></p>
<p><font face="Courier New">public interface Shape {<br />&#160;&#160;&#160; //The method takes a Color type, not integer<br />&#160;&#160;&#160; void applyColor(Color color);<br />}</font>
<p>This enumerated pattern ensures that the Color type is Singleton and provides type safe enumerated constants RED, BLUE, YELLOW, GREEN etc. The toString() method is overriden to provide meaningful information when the constants are printed and the equals() method checks the reference equality of enumerated types, as these are singleton instances.</p>
<p>Is this all enough to define a complete enumerated type? No.</p>
<p><font size="3">Disadvantages of the above enumerated pattern<br /></font>The enumerated pattern approach has the following drawbacks: </p>
<ul>
<li>Enumerated types are not Serializable and Comparable by default<br />Incase, if we make them Serializable, Serialization of Color creates a new instance of the same Color. The equals() method fails to identify the equality of a serialized and a non-serialized Color. (Ofcourse, we can fix this by custom serialization of enumerated types. But, this leads to writing more boiler plate code for each enumerated type)
<li>Color instances cannot be directly used in the switch-case statements, instead you need to use the color value
<li>If a new color is added between existing constants or if the order of Colors is changed, clients must be recompiled. (a.k.a Brittleness)
<li>No support for iterating over the defined enumerated constants</li>
</ul>
<p><font size="3">Java 5 enum</font><br />enum provides a cleaner syntax to define enumerations in Java. And also overcomes all the drawbacks set by the earlier Enumerated pattern.</p>
<ul>
<li>enums are type safe
<li>enums provide default implementation for toString(), equals(), hashCode() methods (Umm.. no extra work)
<li>enums are Comparable and Serializable by default
<li>enums are allowed to be used in switch-case statements
<li>enums are allowed to implement interfaces
<li>Adding new enum constants, does not require re-compilation of the client code
<li>A static values() method is provided that returns an array of defined enumerated constants</li>
</ul>
<p>&#160;</p>
<p>Let us define the Color enumeration using Java 5 enum construct.<br /><font face="Courier New">public enum Color {<br />&#160;&#160;&#160; RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE<br />}</font></p>
<p>The enumerated types RED, BLUE, YELLOW etc. are of type Color.</p>
<p>java.lang.Enum is the supertype of all enums and the Color enum implicitly extends java.lang.Enum. java.lang.Enum provides implementation for equals(), toString(), and hashCode() methods and it implements Serializable and Comparable interfaces. Enums are full-fledged java classes and can have arbitrary methods and fields. Enums can implement interfaces. Enums can have constructors and they take arguments in the declaration as shown below.<br /><font face="Courier New"></font></p>
<p><font face="Courier New">public enum Color {<br />&#160;&#160;&#160; RED(625, 740),<br />&#160;&#160;&#160; ORANGE(590, 625),<br />&#160;&#160;&#160; YELLOW(565, 590),<br />&#160;&#160;&#160; &#8230;</font></p>
<p><font face="Courier New">&#160;&#160;&#160; //Electro-magnetic Spectrum wavelength in nm</font></p>
<p><font face="Courier New">&#160;&#160;&#160; int startWavelength;<br />&#160;&#160;&#160; int endWavelength;<br />&#160;&#160;&#160; Color(start, end) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.startWavelength = start;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; this.endWavelength = end;<br />&#160;&#160;&#160; }<br />&#160;&#160;&#160; public int getStartWavelength() { return startWavelength; }<br />&#160;&#160;&#160; public int getEndWavelength() { return endWavelength; }<br />&#160;&#160;&#160; public static void main(String[] args) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; System.out.println(&#8220;Red color&#8217;s wavelength range, &#8220;<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; + RED.getStartWavelength()+&#8221; ~ &#8220;+RED.getEndWavelength());<br />&#160;&#160;&#160; }<br />}</font></p>
<p>If the Enumerated types have any attributes, a constructor is used to associate these attributes and the Getter methods expose these attributes.</p>
<p><font size="3">Constant specific methods<br /></font>If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant.<br /><font face="Courier New">public enum Color {<br />&#160;&#160;&#160; RED { public Color complimentary() { return GREEN; }},<br />&#160;&#160;&#160; BLUE { public Color complimentary() { return ORANGE; }},<br />&#160;&#160;&#160; YELLOW { public Color complimentary() { return PURPLE; }},<br />&#160;&#160;&#160; &#8230;<br />&#160;&#160;&#160; public abstract Color complimentary();<br />}<br /></font></p>
<p>Each color has its own complementary color and to implement this we can use constant specific methods to return the complementary color. The method complementary() has to be either defined as an abstract method within Color enum or could be a method in one of the implemented interfaces.</p>
<p><font size="3">Restrictions on enum types</font><br />Though enum types are full-fledged classes, the following are not allowed with enums:</p>
<ul>
<li>enums cannot be subclassed
<li>enums cannot have public constructor
<li>enums are not allowed to be instantiated (using new)
<li>enums cannot be cloned</li>
</ul>
<p>All of these are enforced during compile-time.</p>
<p><font size="3">Serialization of enums<br /></font>Serialization mechanism ensures that new enum instances are not created on serialization and de-serialization (ensuring singleton behaviour). In a distributed environment when an enum is serialized from one JVM to another JVM, enum&#8217;s state is not serialized. Hence, it is not encouraged to have state with enums which is updated by the applications. You can only have constant attributes that are initialized by the constructor.</p>
<p><font size="3">Collections built for enums<br /></font>java.util.EnumMap and java.util.EnumSet are the collections added for use with enum types. They provide a compact and efficient implementation for enum types. These collections are not synchronized and when used in multi-threaded environment, applications should take care of synchronizing the operations on the collection.</p>
<p>EnumMap and EnumSet are homogenous collections of the same enum type. They cannot be used to operate on different enum types at the same time.</p>
<p><font face="Courier New"></font></p>
<p><font face="Courier New">public enum Color {<br />&#160;&#160;&#160; RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE; </font>
<p><font face="Courier New">&#160;&#160;&#160; private static EnumSet&#60;Color&#62; primary;<br />&#160;&#160;&#160; private static EnumSet&#60;Color&#62; secondary; </font>
<p><font face="Courier New">&#160;&#160;&#160; public static EnumSet&#60;Color&#62; getPrimaryColors() {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if(primary == null)<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return EnumSet.of(RED, BLUE, YELLOW);<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; return primary;<br />&#160;&#160;&#160; } </font>
<p><font face="Courier New">&#160;&#160;&#160; public static EnumSet&#60;Color&#62; getSecondaryColors() {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; if(secondary == null)<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return EnumSet.complementOf(getPrimaryColors());<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; return secondary;<br />&#160;&#160;&#160; } </font>
<p><font face="Courier New">&#160;&#160;&#160; public static void main(String[] args) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; System.out.println(&#8220;Primary Colors: &#8220;+Color.getPrimaryColors());<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; System.out.println(&#8220;Secondary Colors: &#8220;+Color.getSecondaryColors());<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; System.out.println(&#8220;Universe: &#8220;+EnumSet.allOf(Color.class));<br />&#160;&#160;&#160; }<br />}</font></p>
<p><font face="Courier New"></font>
<p><font size="3">Few gotchas about enums</font><br />However, there are few things which could probably be improved in the coming versions of Java.</p>
<ul>
<li>Currently null can be passed as a method parameter or assigned where an enum is expected. A compile-time verification for null enum assignment would probably avoid all those extra null checks that we need to incorporate in our code.
<li>Static fields within enums cannot be accessed in its constructor. But, static methods are allowed to be invoked. The compiler enforces verification only for static fields and not methods.
<li>However, enum constructors are invoked before static initialization is performed and hence the static fields would not be initialized. So, if you invoke static methods from the constructor which inturn access static fields, they would all be un-initialized.</li>
</ul>
<p><font size="3">Enum syntax</font><br /><font face="Courier New">public enum &#60;your_enum&#62; {<br />&#160;&#160;&#160; &#60;enum_constant1&#62; (&#60;constructor_params&#62;) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; &#60;anonymous_class_declaration&#62;<br />&#160;&#160;&#160; },<br />&#160;&#160;&#160; &#60;enum_constant2&#62; (&#8230;) {&#8230;},<br />&#160;&#160;&#160; &#8230;;<br />&#160;&#160;&#160; //enum constructor [optional]<br />&#160;&#160;&#160; &#60;your_enum&#62; (&#60;constructor_param_defs&#62;) {<br />&#160;&#160;&#160;&#160;&#160;&#160;&#160; //static fields within enum cannot be accessed<br />&#160;&#160;&#160; }<br />&#160;&#160;&#160; &#60;class body&#62; [optional]<br />}</font></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Dalších par ukázek z Javy 5]]></title>
<link>http://jablok.wordpress.com/2005/04/21/1114071483/</link>
<pubDate>Thu, 21 Apr 2005 10:18:03 +0000</pubDate>
<dc:creator>Pavel Kolesnikov</dc:creator>
<guid>http://jablok.wordpress.com/2005/04/21/1114071483/</guid>
<description><![CDATA[Co třeba takovýto (svou jednoduchostí už na úrovni skriptovacích jazyků) kód vypisující řádky textov]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Co třeba takovýto (svou jednoduchostí už na úrovni skriptovacích jazyků) kód vypisující řádky textového souboru:</p>
<pre class="brush: java;">TextFile textfile = new TextFile(new File(f), &quot;UTF-8&quot;);
int lineNumber = 0;
for(String line : textfile) {
   System.out.printf(&quot;%6d: %s%n&quot;, ++lineNumber, line)
} </pre>
<p>Tento příklad a povídání o dalších vybraných novinkách &#8220;Tygří&#8221; javy najdete v článku Davida Flanagan na OnJava.com nazvaném <a href="http://www.onjava.com/pub/a/onjava/2005/04/20/javaIAN5.html">Five Favorite Features from 5.0</a></p>
<p>.</p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
