Saturday, June 5, 2010

Preventing Internet Explorer from caching AJAX requests when using GWT RequestBuilder

I recently spent the best part of a few days trying to work out why some GWT HTTP code I had written was not working (well specifically why it was not working on Internet Explorer). The code was talking to an existing server API that used HTTP GET for a handshake to establish a session-id with the server, and thereafter used HTTP POST to retrieve data. The problem occurred when it attempted to re-handshake. It would always return the same session-id, whereas the server would expect a different session-id. It was all very confusing, until I did some HTTP level tracing and noticed that past the first GET call, the server would never see another GET request.

It turns out, for reasons best known to itself, Internet Explorer will aggressively cache GET requests when using the XMLHttpRequest object. When writing an AJAX application this is particularly painful if you want your result to be dynamic.

If you can modify the server, the best approach is to ensure that the server correctly sets the Cache-Control: no-cache header, but this is not always possible if you are working with a legacy backend.


Another solution is to use an HTTP POST instead, but again that's a problem if you working with existing code, or you are writing to a REST API and you want to keep the GET = Read and POST = Create idiom.


If you want to force the client to get it right this narrows your choices.

A commonly suggested approach is to generate a random request parameter and add this to your request either by appending ?requestId=r4nd0m-v4lu3 to the URI, or if your request already includes parameters appending &requestId=r4nd0m-v4lu3. While this means you won't see the cached responses, the browser still does put these items in the cache, and if you are doing a large number of these requests, this will start to evict things that you actually want to be in there! It may also be a problem if your application enforces strict checking of the passed in parameters.

The best approach I have found is to use the If-Modified-Since header with the date set to the Epoch (1970-01-01 00:00:00 GMT). The browser will not cache the result, and you will not have to worry about clashing with existing parameters. The nice thing about this approach is it is a general solution which you can put in a library and then not worry about problems with the backend.

To do this when using the Google Web Toolkit (GWT) RequestBuilder interface it is simply a matter of using the setHeader method as follows:

void nonCachingHttpGet(String uri, String data, RequestCallback callback)
     RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, uri);
     // This header is required to force Internet Explorer to not cache values from
     // the GET response.
     builder.setHeader("If-Modified-Since", "01 Jan 1970 00:00:00 GMT");
     builder.setHeader("Content-type",
                       "application/x-www-form-urlencoded");
     builder.setCallback(callback);
     builder.send();
}

Monday, May 24, 2010

Writing unit tests when using GWT's Static String Internationalization (I18n) feature

The Google Web Toolkit (GWT) has a fairly simple infrastructure for managing internationalization. While there are a number of different options, the easiest one to use is called Static String Internationalization The basic idea is that you create a properties file for each language and GWT's deferred binding process creates an instance of a Interface which will be loaded depending on the locale. It works something like this:

  1. Create a properties file (e.g. FooConstants.properties). This will contain definitions of the form bar=A string that I want to i18n.
  2. Use the i18nCreator script to generate the Interface definition: i18nCreator -eclipse Foo com.example.foo.client.FooConstants
  3. In your code call GWT.create() to instantiate an instance. e.g:
    public static class MessageDisplayer {
        public MessageDisplayer(Alerter alerter) {
            FooConstants constants = (FooConstants) GWT.create(FooConstants.class);
                alerter.alert(FooConstants.bar());
            }
        }
    }
    
The problem with this is that calling GWT.create from within your code makes it difficult to unit test. If your code calls this directly then you will have to create your unit tests using GWT's Junit3 hack. Running unit tests this way is very slow, and I find it much better to try and factor out as much GWT specific code as possible so that you can write normal boring tests (for example using JUnit 4, or using mocks, or whatever else that GWT tests don't support that takes your fancy). The trick is that if you have any code that relies on an instance of these Constants/Messages files then you are screwed. The solution is to use a DynamicProxy to generate an instance of the interface and then inject these into your code. First we need to refactor our class to have the Constants interface injected, e.g:
public static class MessageDisplayer {
    public MessageDisplayer(Alerter alerter, FooConstants constants) {
        alerter.alert(FooConstants.bar());
    }
}
Next we need to write some code to generate the constants. When the i18nCreator generates the interface it helpfully annotates it with the default text it needs. We can exploit this to generate an instance for testing:
public class ConstantsMocker implements InvocationHandler {
     @SuppressWarnings("unchecked")
     public static <T> T get(Class<? extends T> i18nInterface) {
         return (T) Proxy.newProxyInstance(i18nInterface.getClassLoader(),
                  new Class<?>[] { i18nInterface },
                  new ConstantsMocker());
     }
     public static final String NO_DEFAULT_MESSAGE = "[No Default Message Defined]";

     @Override
     public Object invoke(Object proxy, Method method, Object[] args)
             throws Throwable {
         DefaultMessage message = method.getAnnotation(DefaultMessage.class);
         if (message == null) {
             return NO_DEFAULT_MESSAGE;
         }
         return message.value();
     }
} 
Now when we write our test we can pass down an instance, e.g
@Test
    public void whenConstructorIsCalledAlerterAlertIsCalled {
        AtomicBoolean wasAlerted = new AtomicBoolean(false);
        FooConstants fooConstants = ConstantsMocker.get(FooConstants.class);
        final String expected = fooConstants.bar();
        Alerter alerter = new Alerter() {
            void alert(String msg) {
                assertEquals(expected, msg);
                wasAlerted.set(true);
            }
        }
        new MessageDisplayer(alerter, fooConstants);
        assertTrue(wasAlerted.get());
    }
Whilst this is a toy example it can be a very useful technique if used carefully. Note that regular GWT code just injects the instance from GWT.create() as follows:
MessageDisplayer displayer = 
      new MessageDisplayer(Alerter, (FooConstants)GWT.create(FooConstants.java));

Sunday, May 16, 2010

Creating a bounded LRU Cache with LinkedHashMap

I recently had cause to implement a fixed size cache in some code was writing. I wanted a straightforward map, but with a fixed size and the ability to evict on a least-recently-used (LRU) basis. I thought quickly to get something up and running that I would use a LinkedHashMap and then have my get and put methods use the ordering to implement the LRU policy.

Well it turns out that LinkedHashMap already has this support built-in if you know what you're doing. There are two parts of this jigsaw:

  1. Override the protected removeEldestEntry method which returns a boolean if the eldest entry should be removed. This method is called for every put with the element that
    is eldest according the LRU policy.
  2. Call the LinkedHashMap(int capacity, float loadFactor, boolean accessOrder) constructor. Specifying true for accessOrder means that the order of the elements will be sorted in the order they were last accessed (from least recently used to most recently used).
Putting this together yields:
public class BoundedLruCache<KEY, TYPE> extends LinkedHashMap<KEY, TYPE> {

    private static  final int DEFAULT_INITIAL_CAPACITY = 100;

    private static final float DEFAULT_LOAD_FACTOR = 0.75;

    private final int bound;

    public BoundedLruCache(final int bound) {
        super(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, true);
        this.bound = bound;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<KEY, TYPE> eldest) {
        return size() > bound;
    }
}
Which is remarkably compact. Once again the JRE library proves to have some nice bits and pieces if you know where to look.

Tuesday, April 20, 2010

Collections.addAll for adding an array of elements to a Collection

Shows there is always more that you can learn about the JRE. I have been for ages using the following idiom to add an array of items to a collection:

Collection<Foo> foos = ...;
Foo[] foosToAdd = ...;
foos.addAll(Arrays.asList(foosToAdd);

What I hadn't noticed is that the java.util.Collections class has a static method that does this:

Collection<Foo> foos = ...;
Foo[] foosToAdd = ...;
Collections.addAll(foos, foosToAdd);

Which is not only a little bit simpler but the javadoc says is faster for most implementations of Collection.

Better yet, Collections.addAll takes a variable length argument list and not just a straight array so you can do without the array declaration and just do:

Collection<Foo> foos = ...;
Collections.addAll(foos, foo1, foo2, etc);

See: Collections.addAll Javadoc

Tuesday, July 7, 2009

Switching between 64 bit and 32 bit JVMs in Windows

I run Vista 64 bit on my laptop to get at the ludicrous 6Gb of memory that I seem to need to do my work these days. However I find that because of native library dependencies there are often times when I need to switch between 32 and 64 bit JVMs.

To do so I hacked together this simple batch file which allows you to simply switch JAVA_HOME:

xjava.bat:


@echo off
@rem Allow swiching between 64 and 32 bit versions of jvm.

SET OLD_JAVA_HOME=%JAVA_HOME%

@rem Process switch
set XJAVA_SWITCH=%1
shift
if "%XJAVA_SWITCH%" == "" goto DISPLAY_CURRENT
if "%XJAVA_SWITCH%" == "-64" goto SET_64
if "%XJAVA_SWITCH%" == "-32" goto SET_32
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:SET_32
if "%JAVA_32_HOME%" == "" goto ERROR_32
set JAVA_HOME=%JAVA_32_HOME%
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:ERROR_32
echo Error: JAVA_32_HOME not set.
goto DONE

:SET_64
if "%JAVA_64_HOME%" == "" goto ERROR_64
set JAVA_HOME=%JAVA_64_HOME%
goto DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC

:ERROR_64
echo Error: JAVA_64_HOME not set.
goto DONE

:DISPLAY_CURRENT
@ECHO JAVA_HOME=%JAVA_HOME%
goto DONE

:DISPLAY_JAVA_HOME_AND_CHECK_FOR_CMD_TO_EXEC
@rem Display JAVA_HOME
@ECHO JAVA_HOME=%JAVA_HOME%
if "%JAVA_HOME%" == "%JAVA_32_HOME" echo "Using 32 bit JVM"
if "%JAVA_HOME%" == "%JAVA_64_HOME" echo "Using 64 bit JVM"

@rem Check for java command to execute, otherwise we just set JAVA_HOME
if "%1" == "" goto DONE
set _ARGS=%*
set _ARGS=%_ARGS:-32=%
set _ARGS=%_ARGS:-64=%
"%JAVA_HOME%/bin/java" %_ARGS%
set JAVA_HOME=%OLD_JAVA_HOME%
goto DONE

:DONE



Save as xjava.bat somwhere on your path. You then need to define the environment variables: JAVA_32_HOME and JAVA_64_HOME.

You then use this as follows:

  1. Print the current JAVA_HOME: xjava
  2. Switch to 32 bit VM: xjava -32
  3. Switch to 64 bit VM: xjava -64
  4. Run java with JAVA_HOME set to the appropriate vm: xjava [-32|-64] MyClass

Wednesday, March 18, 2009

Running GWTTestSuite in JUnit 4.4 without the ClassCastException

Running unit tests using the Google Web Toolkit that extends GWTTestCase can be very slow and time consuming, since the JUnitShell has to be restarted for each test. You can speed up testing a lot by instead using GWTTestSuite to group these tests into a single suite than only needs to start the JUnitShell once. The developer's guide gives the following example:
public class MapsTestSuite extends GWTTestSuite {
public static Test suite() {
TestSuite suite = new TestSuite("Test for a Maps Application");
suite.addTestSuite(MapTest.class);
suite.addTestSuite(EventTest.class);
suite.addTestSuite(CopyTest.class);
return suite;
}
}
However, running this using the junit.testui.TestRunner in JUnit4.4 (for example if you are running from the command line using the Maven GWT plugin) gives the following helpful error:

Error: java.lang.ClassCastException


Instead you want to do the following:
public class MapsTestSuite extends TestCase {
public static Test suite() {
GWTTestSuite suite = new GWTTestSuite("Test for a Maps Application");
suite.addTestSuite(MapTest.class);
suite.addTestSuite(EventTest.class);
suite.addTestSuite(CopyTest.class);
return suite;
}
}


i.e. Extend TestCase rather than GWTTestSuite to overcome this problem.

Thursday, November 13, 2008

Duck Typing in Java using Dynamic Proxies

I have a confession to make: I am a lazy typer. And if there is one thing I can't stand it's having to type the same thing more times than I have to. If you had to pick the most useful thing about Object Oriented languages, it would be the fact that using them results in less typing.  And if you had to pick the one concept in OO that makes that possible, polymorphism would be it.  The idea that you can take objects that represent different concepts and treat them similarly is a powerful one, presenting a lot of opportunities for code reuse that would otherwise be difficult or impossible.

In Java, polymorphism (as in other strongly type languages) is achieved by using inheritance, either by having Classes extend a common base class, or by implementing shared interfaces. This allows the compiler to enforce strict checking about which objects can and can not be used polymorphically.

However, there are a number of downsides to requiring inheritance for polymorphism. Sometimes you may be dealing with legacy classes that you cannot change to extend a base class, or implement a specific interface, requiring you to write wrapper classes or adapters. In other cases there may not be a natural common interface leading you to torture your hierarchy to come up with an artificial one.

In addition, requiring classes to implement a specific interface just so that they can be used polymorphically, is unecessary coupling that represents bad design. One of the lessons learnt from Spring and other container frameworks is that there is virtue in not binding yourself to a specific type hierarchy in order to provide generic functionality.  Rather than having classes which either extend abstract classes or implement a bunch of interfaces, you should be able to just write POJOs and have the framework work out what to do with them.  In Spring we use either annotations, convention, or XML mapping files to tell the framework how to make sense of what a particular POJO is attempting to do.  The virtue of this is that you can get the benefits of
running in Spring, without binding yourself to anything about the Spring container. 

In dynamic languages such as Python and Groovy we are able to take a different approach to polymorphism that avoids some of these problems, using a concept known as Duck Typing. Rather than using the type hierarchy to determine whether we can use classes polymorphically, we just assume that if two methods have the same signature, then they probably mean the same thing, ie. rather than determining whether something IS-A duck, we just care that it WALKS-like-a duck and QUACKS-like-a duck[1].

This concept is best illustrated by an example[2].  Suppose we have the following Groovy code:
class Duck {
def quack() { "a loud Quaaaaaaaaaaaaack!" }
def walk() { "waddle" }
}

class Person {
def quack() { "a person making a quacking sound." }
def walk() { "walk" }
}

def tellAStoryAbout(something) {
println "One day while walking in the forest I heard " + something.quack()
println "Intrigued, I turned round to see a dark shape " + something.walk() +
" off into the bushes."
}

tellAStoryAbout(new Duck())
tellAStoryAbout(new Person())
Which generates the following output:
One day while walking in the forest I heard a loud Quaaaaaaaaaaaaack!
Intrigued, I turned round to see a dark shape waddle off into the bushes.
One day while walking in the forest I heard a person making a quacking sound.
Intrigued, I turned round to see a dark shape walk off into the bushes.

We can see here, that using duck typing (which Groovy supports natively), allows us to treat the two classes Person and Duck polymorphically, without requiring them to be part of the same type hierarchy.  This is nice, because in this particular example, it's hard to think of a really good superclass for both a duck and a person that encapsulates this functionality.

Duck Typing in Java

Being that Java is a strongly typed language, providing this sort of Duck Typing support is not exactly straightforward.  Of course it is possible to use reflection to directly invoke the methods on each of the classes, but this is somewhat cumbersome and inelegant.  Another approach is to specify an interface with the methods you wish to use, and then use a Dynamic Proxy to generate an implementation that wraps the classes you wish to invoke methods on.  This has the benefit of a very compact syntax and the fact that as far as consumers of the Duck-typed objects they are just seeing normal interfaces.

To do this we first create a DuckType class with a static factory method:
public static DuckType coerce(Object object)

and then create a single method which will then allow us to specify the type we
wish to coerce to:
 public  T to(Class iface)
This gives us a rather simple syntax for specifying type coercions. We can then
either then pass in already coerced types to methods, e.g:
static import example.DuckType.*;

interface Foo {
String bar();
}

class Bar {
String bar() { "A man walks into a bar..."; }
}

class FooBar {
String bar() { "foo bar baz qux"; }
}


void method(Foo foo) {
System.out.println(foo.bar());
}

method(coerce(new Bar()).to(Foo.class));
method(coerce(new FooBar()).to(Foo.class));
or alternatively we can just have a method take an Object and perform the type
coercion itself, e.g.
static import example.DuckType.*;

interface Foo {
String bar();
}

class Bar {
String bar() { "A man walks into a bar..."; }
}

class FooBar {
String bar() { "foo bar baz qux"; }
}

void method(Object object) {
System.out.println(coerce(object).to(Foo.class).bar());
}

method(new Bar());
method(new FooBar());
Occasionally it's useful to test up front whether a particular class will support the methods we want to call so for this purpose I've added the following method:
public  boolean quacksLikeA(Class iface)
And that's all there is to it. See Appendix A for the full class listing, but for now let's look at some more useful ways to use Duck Typing with this mechanism.

Useful examples


Okay, so those examples were kind of cheesy; let's try doing something useful with
duck typing.  

Copying a Reader/InputStream


In JDK 1.1, Sun introduced the java.io.Reader and java.io.Writer class to deal
properly with some bugs they had introduced when they had written the InputStream class
to handle character encodings.  Because Sun still hadn't worked out exactly how to use 
interfaces correctly both the InputStream and Reader classes are abstract classes.  Code all over the place mixes and matches Reader and InputStream requiring you to handle both cases.

Now suppose you want to write a simple copy function that will handle either a Reader or InputStream and write output to a Writer.  With duck typing it is easy to do this without having
to handle cases for both classes.  First define the interface with the common method you
want to access:
interface Readable {
int read() throws IOException;
}
Next create your copy function taking an Object as the initial parameter and internally coercing to the Readable interface:
static void copy(Object readerOrInputStream, Writer writer) throws IOException {
int b;
Readable readable = coerce(readerOrInputStream).to(Readable.class);
while ((b = readable.read()) != -1) {
writer.write(b);
}
}


Note that not only will this method now work with InputStream and Reader, but with
any other class that has a read method with the same semantics.

Using annotations polymorphically

Another example where polymorphism is difficult in Java is when using JDK 1.5 Annotations. An annotation is a pseudo-interface that represents meta-data about a class (or elements of a class). However, apart from the implictly extended Annotation interface there is no way to access annotations polymorpically. While this is not a big deal for most people, if you find yourself writing code that processes a lot of annotations, you will find yourself writing a bunch of duplicated code to deal with different annotation types.

However, with Duck Typing it becomes possible to write an annotation processor that
can deal polymorphically with annotations.

Let's suppose we are wanting to write a simple persistence layer for some classes
using annotations. We start by adding the following annotations to classes:

@Persistent
@Immutable
@Transient

We will then create a PersistenceHandler strategy interface that will be used by our annotation processor to work out what to do with these annotations:
interface PersistenceHandler {
void persist(Object object);
}

We define the annotations so they include a default handler implementation.
public @interface Persistent {
Class handler() : default PersistentPersistenceHandler.class;
}

public @interface Immutable {
Class handler() : default ImmutableHandler.class;
}

public @interface Transient {
Class handler() : default TransientPersistenceHandler.class;
}
Next we define the interface we are going to use access the handler attribute of
the annotation:
public interface PersistenceAnnotation {
Class handler();
}

And lastly we write our annotation processor:
void processAnnotations(Object object) throws Exception {
for (Annotation annotation : object.getClass().getAnnotations()) {
DuckType annotationToCoerce = coerce(annotation);
if (annotationToCoerce.quacksLikeA(PersistenceAnnotation.class)) {
Class handler =
annotationToCoerce.to(PersistenceAnnotation.class).handler();
handler.newInstance().persist(object);
}
}
}

The nice thing about this is we have completely decoupled our code from which
particular annotations it can support. We can add new annotations as much as we
like, and providing they support the handler() attribute then we can support them. Also we can add other annotations to our classes that we don't handle and these are simply ignored.

Allowing mocking/testing of legacy classes that don't have interfaces

If you are writing your code using Test Driven Development you'll know about the power of mocking and dependency injection to make your code testable. Using a package such as EasyMock it is very easy to quickly create Mocks/Stubs of classes that would be very difficult to otherwise test.

The way these things work is they generate a Dynamic Proxy for the Interface you want to mock and then allow you to specify your expectations of how that class will be called.

That's all well and good, but it assumes that the things you want to mock are already Interfaces[3] and not concrete classes that you have no ability to make changes over.

Sounds like a problem for Duck typing. Let's use for example the java.io.File class. File has a large number of methods, but typically we'll only want to be using a couple of them. Let's define the interface that we want to use:

interface DeleteableFile {
String getName();
String exists();
boolean delete();
}
Now the method we want to test should be written as:
public deleteTmpFileIfExists(Object fileToDelete) {
DeletableFile file = coerce(fileToDelete).to(DeletableFile.class);
if (file.exists() &&
Pattern.matches("(\\.tmp|~)$", file.getName()) {
file.delete();
}
}
We can now test this with a mock using the DeletableFile interface or a standard
File object.

Creating an encrypted String class

One of the decisions made by the early Sun engineers was to make the String class final. This was done mainly for security reasons that I won't bore you with here, but suffice it to say it makes it very difficult to do a lot of extended String classes that add more functionality. Let's suppose we have an encrypted String class that apes the standard String interface:

public final class EncryptedString {
...
}
By now the process for writing methods that handle both this and a standard String should be fairly obvious.  We create the interface with the methods we care about:
interface StringLike {
boolean startsWith(String prefix);
String subString(int beginIndex);
}


And then we use Duck Typing to refer to either:

String skipLeadingSlash(Object stringLikeThing) {
StringLike s = coerce(stringLikeThing).to(StringLike.class);
if (s.startsWith("/")) {
return s.subString(1);
}
}

Parting words

While Duck Typing is a useful concept, it's not all sweetness and light. You do give up a significant amount of compile-time checking to make the concept work. However, if you are practicing Test Driven Development (and give yourself a slap now if you are not), then with good testing you can make this fact largely irrelevant. What duck typing does give you is an incredibly flexible mechanism for polymorphism that buys out many of the disadvantages of inheritance based approaches. Try it in your own code and see what you can do.

Appendix A: DuckType.java code listing


package example;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
* Allows "duck typing" or dynamic invocation based on method signature rather
* than type hierarchy. In other words, rather than checking whether something
* IS-a duck, check whether it WALKS-like-a duck or QUACKS-like a duck.
*
* To use first use the coerce static method to indicate the object you want to
* do Duck Typing for, then specify an interface to the to method which you want
* to coerce the type to, e.g:
*
* public interface Foo {
* void aMethod();
* }
* class Bar {
* ...
* public void aMethod() { ... }
* ...
* }
* Bar bar = ...;
* Foo foo = DuckType.coerce(bar).to(Foo.class);
* foo.aMethod();
*
*
*/
public class DuckType {

private final Object objectToCoerce;

private DuckType(Object objectToCoerce) {
this.objectToCoerce = objectToCoerce;
}

private class CoercedProxy implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Method delegateMethod = findMethodBySignature(method);
assert delegateMethod != null;
return delegateMethod.invoke(DuckType.this.objectToCoerce, args);
}
}

/**
* Specify the duck typed object to coerce.
*
* @param object the object to coerce
* @return
*/
public static DuckType coerce(Object object) {
return new DuckType(object);
}

/**
* Coerce the Duck Typed object to the given interface providing it
* implements all the necessary methods.
*
* @param
* @param iface
* @return an instance of the given interface that wraps the duck typed
* class
* @throws ClassCastException if the object being coerced does not implement
* all the methods in the given interface.
*/
public T to(Class iface) {
assert iface.isInterface() : "cannot coerce object to a class, must be an interface";
if (isA(iface)) {
return iface.cast(objectToCoerce);
}
if (quacksLikeA(iface)) {
return generateProxy(iface);
}
throw new ClassCastException("Could not coerce object of type "
+ objectToCoerce.getClass() + " to " + iface);
}

private boolean isA(Class iface) {
return objectToCoerce.getClass().isInstance(iface);
}

/**
* Determine whether the duck typed object can be used with
* the given interface.
*
* @param Type of the interface to check.
* @param iface Interface class to check
* @return true if the object will support all the methods in the
* interface, false otherwise.
*/
public boolean quacksLikeA(Class iface) {
for (Method method : iface.getMethods()) {
if (findMethodBySignature(method) == null) {
return false;
}
}
return true;
}

@SuppressWarnings("unchecked")
private T generateProxy(Class iface) {
return (T) Proxy.newProxyInstance(iface.getClassLoader(),
new Class[] { iface }, new CoercedProxy());
}

private Method findMethodBySignature(Method method) {
try {
return objectToCoerce.getClass().getMethod(method.getName(),
method.getParameterTypes());
} catch (NoSuchMethodException e) {
return null;
}
}

}

Footnotes


[1] Attributed to Alex Martelli in a message to the comp.lang.python newsgroup [Wikipedia].
[2] Adapted from the example in the [Wikipedia Duck Typing Article.
[3] More recent versions of EasyMock do class instrumentation to overcome this limitation, but we'll ignore that for now.