Thursday, January 12, 2006

java code you shouldn't need, but sometimes do


/*
* DoNothing.java
*
*/

import java.lang.reflect.*;
import java.util.Arrays;

/**
* Creates a dynamic proxy that simply does nothing and returns null
* or "0", when any of its methods are called.
*/
public class DoNothing implements InvocationHandler {

/**
* Creates a do-nothing proxy that implements all the interfaces.
*/
public static Object newInstance(Class[] interfaces) {
return Proxy.newProxyInstance(DoNothing.class.getClassLoader(), interfaces, new DoNothing());
}

/**
* Creates a do-nothing proxy that implements one interface.
*/
public static Object newInstance(Class iface ) {
return newInstance( new Class[]{iface});
}


public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Class returnType = method.getReturnType();

// if the method isn't supposed to return anything,
// return null
if(returnType == void.class) {
return null;
}

// if we have a return value, return whatever it is
// that new arrays of our return type are filled with.
// this is a convenient way to get "0" as the right
// kind of primitive, or null for objects, in one
// line of code.
return Array.get( Array.newInstance(returnType,1), 0);
}


}

Comments: