A bit of fun with duck typing in Java.

February 13, 2009

This is just a bit of fun I had in Java based on some of the ideas we’ve been coming up with on Chem4Word in C#.

The basic idea is to implement “kind-of” duck typing in statically typed languages. That is, you might want to define an interface, see whether object classes already implement it, and if they do, you can pretend they implemented that interface when they were written. It’s a possibly correct, certainly naiive implementation, but it illustrates generic methods and a corner of the reflection API, so it might be instructive to some.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class DuckType {

public static T cast(final Object obj, Class cl) {
Method[] methods = cl.getMethods();
final Map methodMap = new HashMap(
Class objClass = obj.getClass();
boolean implemented = true;
for (Method m : methods) {
try {
Method targetM = objClass.getMethod(m.getName(), m
if (targetM.getReturnType().isAssignableFrom(m.getReturnType())) {
methodMap.put(m, targetM);
} else {
implemented = false;
} catch (NoSuchMethodException e) {
implemented = false;
if (implemented) {
return (T) Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), new Class[] { cl },
new InvocationHandler() {
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
Method targetMethod = methodMap.get(method);
return targetMethod.invoke(obj, args);
} else {
// Alternatively you could throw a ClassCastException earlier and never get here.
return null;




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: