<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Java Clippings</title>
	<atom:link href="http://javaclippings.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://javaclippings.wordpress.com</link>
	<description>Useful snippets of Java code</description>
	<lastBuildDate>Sun, 14 Aug 2011 07:43:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='javaclippings.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Java Clippings</title>
		<link>http://javaclippings.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://javaclippings.wordpress.com/osd.xml" title="Java Clippings" />
	<atom:link rel='hub' href='http://javaclippings.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Script variables</title>
		<link>http://javaclippings.wordpress.com/2011/08/10/script-variables/</link>
		<comments>http://javaclippings.wordpress.com/2011/08/10/script-variables/#comments</comments>
		<pubDate>Wed, 10 Aug 2011 07:28:04 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Scripting]]></category>
		<category><![CDATA[javax-script]]></category>
		<category><![CDATA[rhino]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=73</guid>
		<description><![CDATA[In my previous post, I showed how the parameters to a JavaScript function can be supplied with Java. The next step is to supply other variables. The simplest way to set some variable values is to use ScriptEngine.put(name, value): ScriptEngine engine = ...; engine.put("taxRate", 0.0825); // 8.25% // evaluate script // invoke function Now the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=73&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://javaclippings.wordpress.com/2011/08/09/invoke-js-function/" title="Invoking a function defined in JavaScript">previous post</a>, I showed how the parameters to a JavaScript function can be supplied with Java. The next step is to supply other variables.</p>
<p>The simplest way to set some variable values is to use <a href="http://download.oracle.com/javase/6/docs/api/javax/script/ScriptEngine.html#put(java.lang.String, java.lang.Object)"><code>ScriptEngine.put(name, value)</code></a>:</p>
<pre>
  ScriptEngine engine = ...;
  engine.put("taxRate", 0.0825); // 8.25%
  // evaluate script
  // invoke function
</pre>
<p>Now the hardcoded tax rate in the previous script can be replaced with a variable:</p>
<pre style="border-style:dashed;border-width:1px;padding:5px;">// userdef.js
function expectedSalesTax(productType, unitPrice, quantity) {
  return unitPrice * quantity * taxRate;
}</pre>
<p>The variables&#8217; values are not limited to simple types like strings and primitives. And the ability to introduce any Java object into the script environment greatly expands the integration&#8217;s usefulness. For example, the script can use a product knowledge base:</p>
<pre style="border-style:dashed;border-width:1px;padding:5px;">// userdef.js
function expectedSalesTax(productType, unitPrice, quantity) {
  return productKb.isExemptFromSalesTax(productType)
         ? 0
         : unitPrice * quantity * taxRate;
}</pre>
<pre>
public class ProductKB {
  public boolean isExemptFromSalesTax(Object productInfo) {
    return contains(productInfo, "clothes");
  }
  private boolean contains(Object collection, String item) {
    if (collection instanceof Collection) {
      return ((Collection) collection).contains(item);
    } else {
      String stringForm = ';' + String.valueOf(collection) + ';';
      return stringForm.indexOf(';' + item + ';') &gt;= 0;
  }
}

public class Demo {
  public static void main(...) throws ... {
    ProductKB productKb = new ProductKB();
    ScriptEngine engine = ...;
    engine.put("taxRate", 0.0825); // 8.25%
    engine.put("productKb", productKb);
    engine.eval(...);

    Invocable invocable = (Invocable) engine;
    invocable.invokeFunction("expectedSalesTax",
                             Arrays.asList("clothes", "winter"),
                             89.95, 2); // 0.0
    invocable.invokeFunction("expectedSalesTax",
                             Arrays.asList("sneakers", "basketball"),
                             102.1, 3); // 25/26975
  }
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/73/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=73&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2011/08/10/script-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Invoking a function defined in JavaScript</title>
		<link>http://javaclippings.wordpress.com/2011/08/09/invoke-js-function/</link>
		<comments>http://javaclippings.wordpress.com/2011/08/09/invoke-js-function/#comments</comments>
		<pubDate>Tue, 09 Aug 2011 09:10:00 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Scripting]]></category>
		<category><![CDATA[javax-script]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=63</guid>
		<description><![CDATA[Picking up where I left off in the previous post, I am going to cover some ways to get data into a script. Here&#8217;s how to simply supply parameter values when calling a function defined in a script. First the ScriptRunner needs to be updated: pubic class ScriptRunner { ... public void load(String scriptName) throws [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=63&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Picking up where I left off in the <a href="http://javaclippings.wordpress.com/2011/08/04/js-from-java/">previous post</a>, I am going to cover some ways to get data into a script.</p>
<p>Here&#8217;s how to simply supply parameter values when calling a function defined in a script. First the <code>ScriptRunner</code> needs to be updated:</p>
<pre>pubic class ScriptRunner {
  ...

  public void load(String scriptName) throws ... {
    Reader reader = resourceReader(scriptName);
    _engine.eval(reader);
  }

  public &lt;T&gt; T invoke(String functionName, Object... params) throws ... {
    //noinspection unchecked
    return (T) ((Invocable) _engine).invokeFunction(functionName, params);
  }

  private InputStreamReader resourceReader(String scriptName) {
    InputStream stream = getClass().getResourceAsStream(scriptName);
    return new InputStreamReader(stream);
  }
}</pre>
<p>Now, given some script:</p>
<pre style="border-style:dashed;border-width:1px;padding:5px;">// userdef.js
function expectedSalesTax(productType, unitPrice, quantity) {
  return unitPrice * quantity * 0.0825;   // 8.25%
}</pre>
<p>It can be invoked after the script is loaded:</p>
<pre>  ScriptRunner runner = new ScriptRunner();
  runner.load("userdef.js");
  double taxes = runner.invoke("expectedSalesTax", "sneakers", 99.90, 5);</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/63/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/63/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/63/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=63&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2011/08/09/invoke-js-function/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Running a JavaScript file from Java</title>
		<link>http://javaclippings.wordpress.com/2011/08/04/js-from-java/</link>
		<comments>http://javaclippings.wordpress.com/2011/08/04/js-from-java/#comments</comments>
		<pubDate>Thu, 04 Aug 2011 06:06:05 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Scripting]]></category>
		<category><![CDATA[javax-script]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=56</guid>
		<description><![CDATA[I gravitate towards writing testing infrastructure. I find it very rewarding to see my frameworks, abstractions and convenience APIs being used by my coworkers. As the testing gets further and further away from unit tests, having scripting capabilities tends to become increasingly important. In the past, I&#8217;ve used BeanShell, jython and various DSLs to support [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=56&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I gravitate towards writing testing infrastructure. I find it very rewarding to see my frameworks, abstractions and convenience APIs being used by my coworkers. As the testing gets further and further away from unit tests, having scripting capabilities tends to become increasingly important.</p>
<p>In the past, I&#8217;ve used BeanShell, jython and various DSLs to support test scripts. Recently, I&#8217;ve started using Java 6&#8242;s embedded &#8216;Rhino&#8217; JavaScript engine.</p>
<p>In a series of posts, I want to share some basics of how you can enable cross-interactions between some Java code and some JavaScript.</p>
<p>I started with a basic script runner facade:</p>
<pre>import javax.script.*;

public class ScriptRunner {
  private final ScriptEngineManager _manager;
  private final ScriptEngine _engine;

  public ScriptRunner() {
    _manager = new ScriptEngineManager();
    _engine = _manager.getEngineByName("JavaScript");
  }

  public Object run(String scriptName) throws ... {
    Reader reader = new InputStreamReader(getClass().getResourceAsStream(scriptName));
    return _engine.eval(reader);
  }
}</pre>
<p>For simplicity, I placed this near-trivial script file in the classpath:</p>
<pre style="border-style:dashed;border-width:1px;padding:5px;">// hello_world.js
function myconcat(a, b) { return a + ' ' + b; }
myconcat('hello', 'world');</pre>
<p>&#8230; and ran the script:</p>
<pre>  public static void main(...) throws ... {
    ScriptRunner runner = new ScriptRunner();
    runner.run("hello_world.js");
  }</pre>
<p>which produced the expected</p>
<blockquote style="color:white;background-color:black;padding:5px;"><p>hello world</p></blockquote>
<p>No additional libraries, broadly and well understood script language&#8230; so a promising start.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/56/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=56&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2011/08/04/js-from-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Java Dynamic Proxies &#8211; equals(), hashCode(), toString()</title>
		<link>http://javaclippings.wordpress.com/2009/03/18/dynamic-proxies-equals-hashcode-tostring/</link>
		<comments>http://javaclippings.wordpress.com/2009/03/18/dynamic-proxies-equals-hashcode-tostring/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 09:14:58 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=45</guid>
		<description><![CDATA[Some meaty documentation for dynamic proxies can be found in the javadoc for java.lang.reflect.Proxy. One detail specifically called out is how calls to a proxy instance&#8217;s equals(), hashCode() and toString() are dispatched to the invocation handler. The design subtlety turns out be important and well thought-out. To understand why, it is first important to grasp [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=45&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Some meaty documentation for dynamic proxies can be found in the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html">javadoc for <tt>java.lang.reflect.Proxy</tt></a>.</p>
<p>One detail specifically called out is how calls to a proxy instance&#8217;s equals(), hashCode() and toString() are dispatched to the invocation handler. The design subtlety turns out be important and well thought-out. To understand why, it is first important to grasp the behavior of <tt>java.lang.reflect.Method</tt>&#8216;s <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Method.html#getDeclaringClass()"><tt>getDeclaringClass()</tt></a>.</p>
<p>Usually, if a method <tt>m()</tt> of some class <tt>A</tt> is overridden in a subclass <tt>B</tt>, then the subclass&#8217;s method&#8217;s declaring class is <tt>B</tt>. The junit test code snippet below demonstrates this point:</p>
<pre>    public void testStockEqualsMethod() {
        assertSame(Object.class,
                   getEqualsMethod(new Object()).getDeclaringClass());
    }

    public void testEqualsMethodOverridden() {
        assertSame(Integer.class,
                   getEqualsMethod(new Integer(1)).getDeclaringClass());
    }

    private Method getEqualsMethod(Object o) {
        try {
            return o.getClass().getMethod("equals", Object.class);
        }
        catch (NoSuchMethodException e) {
            fail("Developer assumption violated; single arg equals is always available.");
            throw new Error(); // never happens; fail() throws its own exception.
        }
    }</pre>
<p>A similar thing happens with dynamic proxies. The test code below illustrates the similarity. Note that in the second test method, the proxy implements interface <tt>B</tt>, and that the assert checks for a declaring class <tt>B</tt>:</p>
<pre>    interface A {
        void someMethod();
    }

    public void testInterfaceMethod() {
        A proxy = newProxyInstance(A.class, new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) {
                assertSame(A.class, method.getDeclaringClass());
                return null;
            }
        });
        proxy.someMethod();
    }

    interface B extends A {
        void someMethod();
    }

    public void testRedefiningInterfaceMethod() {
        A proxy = newProxyInstance(<strong>B.class</strong>, new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) {
                assertSame(<strong>B.class</strong>, method.getDeclaringClass());
                return null;
            }
        });
        proxy.someMethod();
    }</pre>
<p>If the same behavior were to happen for <tt>equals</tt>, <tt>hashCode</tt> and <tt>toString</tt>, then the invocation handler would need to accommodate cases where some interface redefines one or more of those methods. (An example such a redefinition is <tt>java.util.List</tt>, where equality is declared to be concrete type agnostic and element order sensitive.)</p>
<p>Instead, invocation handlers can simply have a flow branch for special casing the three methods. The code below demonstrates how the methods should be special-cased for the implementation hiding example <a href="http://javaclippings.wordpress.com/2009/03/16/java-dynamic-proxies-basic/">posted previously</a>:</p>
<pre>    private static class EqualsAwareHandler&lt;T&gt; implements InvocationHandler {
        private static final Method OBJECT_EQUALS =
            getObjectMethod("equals", Object.class);

        private static final Method OBJECT_HASHCODE =
            getObjectMethod("hashCode");

        private final T _implementation;

        EqualsAwareHandler(final T implementation) {
            _implementation = implementation;
        }

        public Object invoke(Object proxy, Method method, Object[] objects)
            throws Throwable {
            if (OBJECT_EQUALS == method) {
                return equalsInternal(proxy, objects[0]);
            }

            if (OBJECT_HASHCODE == method) {
              return _implementation.hashCode();
            }
            // toString() will fall through to the generic handling.
            try {
                return method.invoke(_implementation, objects);
            }
            catch (InvocationTargetException itx) {
                throw itx.getTargetException();
            }
        }

        private boolean equalsInternal(Object me, Object other) {
            if (other == null) {
                return false;
            }
            if (other.getClass() != me.getClass()) {
                // Not same proxy type; false.
                // This may not be true for other scenarios.
            }
            InvocationHandler handler = Proxy.getInvocationHandler(other);
            if (!(handler instanceof EqualsAwareHandler)) {
                // the proxies behave differently.
                return false;
            }
            return ((EqualsAwareHandler) handler)._implementation.equals(_implementation);
        }

        private static Method getObjectMethod(String name, Class... types) {
            try {
                // null 'types' is OK.
                return Object.class.getMethod(name, types);
            }
            catch (NoSuchMethodException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=45&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2009/03/18/dynamic-proxies-equals-hashcode-tostring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Learning Java Dynamic Proxies &#8211; Basics</title>
		<link>http://javaclippings.wordpress.com/2009/03/16/java-dynamic-proxies-basic/</link>
		<comments>http://javaclippings.wordpress.com/2009/03/16/java-dynamic-proxies-basic/#comments</comments>
		<pubDate>Mon, 16 Mar 2009 09:26:16 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=37</guid>
		<description><![CDATA[Java 1.3 introduced java.lang.reflect.Proxy, which allows code to dynamically implement interfaces. This is done by asking Java to create a proxy around an InvocationHandler that you define. Whenever a method on the proxy is invoked, the proxy delegates the invocation to the invocation handler. For example, the call someMethod("arg1", "arg2") is invoked on proxy3 would [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=37&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Java 1.3 introduced <tt>java.lang.reflect.Proxy</tt>, which allows code to dynamically implement interfaces. This is done by asking Java to create a proxy around an <tt>InvocationHandler</tt> that you define. Whenever a method on the proxy is invoked, the proxy delegates the invocation to the invocation handler. For example, the call <tt>someMethod("arg1", "arg2")</tt> is invoked on <tt>proxy3</tt> would result in the associated invocation handler being called with <tt>invoke(proxy3, "someMethod", new Object[] { "arg1", "arg2" })</tt>. I always think of dynamic proxies as the complement to reflection.  Reflection allows a single method call (<tt>Method.invoke(...)</tt>) to be directed to any number of methods. With dynamic proxies, various different methods&#8217; calls converge to the same handler method (<tt>InvocationHandler.invoke(...)</tt>).</p>
<p>The easiest practical demonstration of a dynamic proxy focuses on hiding implementations from clients. When I say &#8216;hiding&#8217;, I mean preventing clients from downcasting and even preventing them from getting anything useful out of <tt>instance.getClass()</tt>. Here&#8217;s how one would start such a proxy:</p>
<pre>
    public  T rudimentaryHideImplementation(T implementation) {
        if (null == implementation) {
            return null;
        }
        final ClassLoader loader = implementation.getClass().getClassLoader();
        final Class[] interfaces = getImplementedInterfaces(implementation);
        final InvocationHandler handler = new RudimentaryHandler(implementation);
        return (T) Proxy.newProxyInstance(loader, interfaces, handler);
    }

    private static Class[] getImplementedInterfaces(Object implementation) {
        return implementation.getClass().getInterfaces();
    }

    private static class RudimentaryHandler implements InvocationHandler {
        private final T _implementation;

        RudimentaryHandler(final T implementation) {
            _implementation = implementation;
        }

        public Object invoke(Object proxy,
                             Method method,
                             Object[] objects)
            throws Throwable {
            try {
                return method.invoke(_implementation, objects);
            }
            catch (InvocationTargetException itx) {
                throw itx.getTargetException();
            }
        }
    }
</pre>
<p>In the above code, <tt>getImplementedInterfaces(...)</tt> was oversimplified. Specifically, <tt>interfaces[]</tt> will only contain the interfaces implemented by the instance&#8217;s class; it will not contain interfaces imeplemented by its superclasses. Here&#8217;s a more correct version:</p>
<pre>
    private  Class[] getImplementedInterfaces(Object implementation) {
        LinkedHashSet interfaces = new LinkedHashSet();
        for (Class c = implementation.getClass(); c != null; c = c.getSuperclass()) {
            interfaces.addAll(Arrays.asList(c.getInterfaces()));
        }
        return interfaces.toArray(new Class[interfaces.size()]);
    }
</pre>
<p>Any reflection gurus will tell you that I&#8217;ve also oversimplified the code inside the invocation handler. True. I will cover those details in Part 2.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/37/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=37&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2009/03/16/java-dynamic-proxies-basic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Handy Convenience Methods with Varargs and Generic Methods</title>
		<link>http://javaclippings.wordpress.com/2009/03/05/convenient-varargs/</link>
		<comments>http://javaclippings.wordpress.com/2009/03/05/convenient-varargs/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 07:43:29 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Quick Tip]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=23</guid>
		<description><![CDATA[Convenient ways to instantiate genericized types, pre-populated Lists, Sets and Java arrays using varargs and generic methods. These are very useful when writing code that needs to create several collections of pre-defined content, unit tests being classic examples.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=23&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When I&#8217;m dealing with code that uses collections or arrays, I often find myself writing these convenience methods. This is especially true within unit tests, where reducing <a href="http://en.wikipedia.org/wiki/Signal-to-noise_ratio">SnR</a> is very important.</p>
<p>The first one is for creating an empty list, set, or map etc without having to duplicate the template parameters. Here it&#8217;s written for a HashMap:</p>
<pre>private static &lt;K, V&gt; Map&lt;K, V&gt; newHashMap() {
    return new HashMap&lt;K, V&gt;();
}
</pre>
<p>It can be used as follows:</p>
<pre>// would have had to write
// private final Map&lt;UserId, Set&lt;PhoneNumber&gt;&gt; _phByUserId =
//       new HashMap&lt;UserId, Set&lt;PhoneNumber&gt;&gt;();
// instead we can simplify to
private final Map&lt;UserId, Set&lt;PhoneNumber&gt;&gt; _phByUserId = newHashMap();
</pre>
<p>The next method is used to instantiate and populate a list or a set:</p>
<pre>private static &lt;T&gt; Set&lt;T&gt; toHashSet(T... elements) {
    Set set = new HashSet&lt;T&gt;();
    for (T element : elements) {
        set.add(element);
    }
    return set;
}
</pre>
<p>The varargs lend the method to elegant use:</p>
<pre>Set&lt;String&gt; resourceNames =
    toHashSet(
      "simple_request.xml",
      "malformed_request.xml",
      "incomplete_request.xml"
    );
</pre>
<p>A similar method can be written for instantiating pre-populated lists. If you know that the list will never be added to, you can forgo writing any convenience method, and use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#asList(T...)"><tt>java.util.Arrays</tt></a> directly:</p>
<pre>import static java.util.Arrays.asList;
...
List&lt;String&gt; resourceNames =
    asList(
      "simple_request.xml",
      "malformed_request.xml",
      "incomplete_request.xml"
    );
</pre>
<p>The last also happens to be my favorite. Instantiating pre-populated arrays in Java involves far too much typing. For example:</p>
<pre>Class[] interfaces = new Class[] { Person.class, Customer.class };</pre>
<p>Using the following simple convenience&#8230;</p>
<pre>private static &lt;T&gt; T[] array(T... elements) {
    return elements;
}
</pre>
<p>&#8230; The earlier expression can be replaced with:</p>
<pre>Class[] interfaces = array(Person.class, Customer.class);</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/23/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/23/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/23/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=23&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2009/03/05/convenient-varargs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>A Case of Dynamic Dispatching</title>
		<link>http://javaclippings.wordpress.com/2009/02/16/dynamic-dispatching/</link>
		<comments>http://javaclippings.wordpress.com/2009/02/16/dynamic-dispatching/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 07:45:16 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=16</guid>
		<description><![CDATA[In my previous post, I (intentionally) omitted various important technical and theoretical details. Here, I look at the concept of Dynamic Dispatching, and how it fits with the simple prettyToString() example. Dynamic dispatching is what makes polymorphic behavior happen. When you call toString() on an object, the right implementation is called because Java dispatches to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=16&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my <a href="/2009/01/23/avoid-multiple-if-else-ifs-part1/">previous post</a>, I (intentionally) omitted various important technical and theoretical details. Here, I look at the concept of <em>Dynamic Dispatching</em>, and how it fits with the simple <tt>prettyToString()</tt> example.</p>
<p><a href="http://en.wikipedia.org/wiki/Dynamic_dispatch">Dynamic dispatching</a> is what makes polymorphic behavior happen. When you call <tt>toString()</tt> on an object, the right implementation is called because Java dispatches to the appropriate method based on the type of the instance. But Java doesn&#8217;t go the whole length when it comes to dynamic dispatch: while it pays attention to the actual type of the instance, it only concerns itself with the type of the <strong>reference</strong> to any parameters, <strong>not their actual types</strong>. For example:</p>
<pre>abstract class PrettyPrinter {
  abstract void prettyPrint(Number n);
  abstract void prettyPrint(Long l);
  abstract void prettyPrint(Double d);
}

final class AmericanPrettyPrinter extends PrettyPrinter { ... }

final class ItalianPrettyPrinter extends PrettyPrinter { ... }

PrettyPrinter printer = new AmericanPrettyPrinter();
Double d = new Double(34.5);
Number n = d;
printer.prettyPrint(d); // uses AmericanPrettyPrinter.prettyPrint(Double d);
printer.prettyPrint(n); // uses AmericanPrettyPrinter.prettyPrint(Number n);</pre>
<p>Yes, this is painfully obvious. I am trying to highlight the asymmetry: while the instance&#8217;s type is considered at runtime but the parameter&#8217;s type is not. Some languages do not have this limitation; Java does.</p>
<p>The previous post&#8217;s if-elseif- sequence is one way of accommodating this limitation. Here&#8217;s a more complete list of approaches one might employ:</p>
<p><strong>1. If the method in question doesn&#8217;t require parameters, you can simply use the dynamic dispatching supported by Java.</strong> There are two reasons to not do so. First, you may not be the author of the classes. In the above example, you cannot add <tt>public abstract String toPrettyString()</tt> to <tt>java.lang.Number</tt>, nor can you add concrete implementations of the method to <tt>java.lang.Double</tt> and <tt>java.lang.Long</tt>. Second, you may choose to not add the method &#8220;family&#8221; for coupling &amp; cohesion reasons: you may not want to add various disparate methods like <tt>toPrettyString()</tt>, <tt>toDebugString()</tt>, <tt>toXmlString()</tt> etc., because your core classes&#8217; code gets polluted with a plethora of specialized logic.</p>
<p><strong>2. Use traditional flow control constructs like <code>if-else</code> or <code>switch-case</code>.</strong> When there are very few code path alternatives, this solution &#8212; however distasteful to purists &#8212; is often suitable.</p>
<p><strong>3. Use a double dispatch idiom.</strong> The idiom looks like this:</p>
<pre>interface ContactInfoVisitor {
  void handlePhysicalAddress(PhysicalAddress pa);
  void handlePhoneNumber(PhoneNumber pn);
  void handleEmailAddress(EmailAddress ea);
}

abstract class ContactInfo {
  abstract void visit(ContactInfoVisitor v);
}

class PhysicalAddress extends ContactInfo {
  void visit(ContactInfoVisitor v) {
    v.handlePhysicalAddress(this);
  }
}

class PhoneNumber extends ContactInfo {
  void visit(ContactInfoVisitor v) {
    v.handlePhoneNumber(this);
  }
}

class EmailAddress extends ContactInfo {
  void visit(ContactInfoVisitor v) {
    v.handleEmailAddress(this);
  }
}</pre>
<p>This is an application of what the Gang-of-Four call the <a href="http://en.wikipedia.org/wiki/Visitor_pattern">Visitor Pattern</a>. Once again, you need access to your parameter classes (in the above example, all <tt>ContactInfo</tt> types). Furthermore, this approach requires that all code (the parameter types, the visitor interface and visitor implementations) be compiled at the same time. Post a comment if you are interested why this is, or if you seek techniques to relax this limitation.</p>
<p><strong>4. Implement some dynamic dispatching solution yourself. </strong> Classification-based, type-based and defaulting-based are some popular implementation approaches. The <a href="/2009/01/23/avoid-multiple-if-else-ifs-part1/">previous post</a> introduced a simple defaulting-based dispatching.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/16/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/16/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/16/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=16&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2009/02/16/dynamic-dispatching/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
		<item>
		<title>Avoiding multiple &#8220;if-else if&#8221;s using functors Part 1</title>
		<link>http://javaclippings.wordpress.com/2009/01/23/avoid-multiple-if-else-ifs-part1/</link>
		<comments>http://javaclippings.wordpress.com/2009/01/23/avoid-multiple-if-else-ifs-part1/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 10:06:53 +0000</pubDate>
		<dc:creator>dranatunga</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://javaclippings.wordpress.com/?p=8</guid>
		<description><![CDATA[Scenario: Sometimes, we need to add a behavior to several classes, where we cannot modify the classes. For example, imagine wanting to add prettyToString() to Strings, Numbers, Booleans, Collections and Maps. A first stab at the code may look like this: public static String prettyToString(Object input) { if (input instanceof String) { return prettyToString((String) input); [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=8&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Scenario</strong>:</p>
<p>Sometimes, we need to add a behavior to several classes, where we cannot modify the classes. For example, imagine wanting to add <tt>prettyToString()</tt> to Strings, Numbers, Booleans, Collections and Maps.</p>
<p>A first stab at the code may look like this:</p>
<pre>
public static String prettyToString(Object input) {
  if (input instanceof String) {
    return prettyToString((String) input);
  } else if (input instanceof Number) {
    return prettyToString((Number) input);
  } else if (input instanceof Boolean) {
    return prettyToString((Boolean) input);
  } else if (input instanceof Collection) {
    return prettyToString((Collection) input);
  } else if (input instanceof Map) {
    return prettyToString((Map) input);
  }
    return "instance of " + input.getClass().getName();
}

private static String prettyToString(String string) { ... }

private static String prettyToString(Number number) { ... }
...
</pre>
<p><strong>Problem</strong>:</p>
<p>The if-else blocks become unwieldy very quickly.</p>
<p><strong>Simple Improvement</strong>:</p>
<p>Define a base type for a family of functors. Each concrete functor knows how to handle one of the condition blocks. When the general method is called, it tries to use each of the functors in turn until one formats the object. If they all fail, then the default formatting is performed.</p>
<pre>
private static final List&lt;PrettyToString&gt; PRETTY_TO_STRING = buildPrettyToStringHandlers();

public static String prettyToString(Object input) {
  for (PrettyToString functor : PRETTY_TO_STRING) {
    String formatted = functor.handleIfPossible(input);
    if (formatted != null) {
      return formatted;
    }
  }
  return "instance of " + input.getClass().getName();
}

private static String prettyToString(String string) { ... }

private static String prettyToString(Number number) { ... }

private static List&lt;PrettyToString&gt; buildPrettyToStringHandlers() {
  List&lt;PrettyToString&gt; m = new ArrayList&lt;PrettyToString&gt;();
  m.add(new PrettyToString&lt;String&gt;(String.class) {
    String handle(String string) { return prettyToString(string); }
  });
  m.add(new PrettyToString&lt;Number&gt;(Number.class) {
    String handle(Number number) { return prettyToString(number); }
  });
  ...
  return Collections.unmodifiableList(m);
}

private static abstract class PrettyToString&lt;T&gt; {
  private final Class&lt;T&gt; _type;

  PrettyToString(Class&lt;T&gt; type) {
    _type = type;
  }

  final String handleIfPossible(Object object) {
    return _type.isInstance(object) ? handle(_type.cast(object)) : null;
  }

  abstract String handle(T object);
}
</pre>
<p><strong>Notes:</strong></p>
<p>This is a well known technique. Looking through the Gang of Four&#8217;s behavioral design patterns, I see that this is a variation of a &#8220;Chain of Responsibility&#8221; pattern.</p>
<p>This approach &#8212; and the additional code &#8212; becomes defensible when the list of functors is determined at runtime. It does not, however, buy an improvement in code. After all, we&#8217;ve removed a single sprawling if-else-if block but <em>added a bunch of inner classes, a static builder method and a static member</em>. Furthermore, we&#8217;ve harmed performance.</p>
<p>Part 2 will build on this approach but address the deficiencies.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javaclippings.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javaclippings.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javaclippings.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javaclippings.wordpress.com&amp;blog=6287161&amp;post=8&amp;subd=javaclippings&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://javaclippings.wordpress.com/2009/01/23/avoid-multiple-if-else-ifs-part1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/7025f4badf651767a88080e351e3089c?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">dranatunga</media:title>
		</media:content>
	</item>
	</channel>
</rss>
