Thursday, June 16, 2005

C# type delegates in java

Well - if you like me ever wanted something much like the C# delegate or a pointer to a method, in java - this might be for you. Its not quite there, but this is as close as I could come... Written in notepad on a cloudy evening..



import java.lang.reflect.*;

public class Test
{


public void objectCallback(String parameter)
{
System.out.println("objectCallback("+parameter+")");
}

public static void instanceCallback(String parameter)
{
System.out.println("instanceCallback("+parameter+")");
}

public void add(int val1, int val2, Delegate delegate)
{
int result = val1 + val2;
try {
delegate.delegate(new Object[] { String.valueOf(result) });
} catch (Exception e) {
e.printStackTrace();
}
}


public static void main(String[] args) {
System.out.println("Test start");
Test test = new Test();
test.add(3, 3, new Delegate(test, "objectCallback"));
test.add(3, 3, new Delegate(Test.class, "instanceCallback"));
System.out.println("Test end");
}


public static class Delegate
{
private String methodName;
private Class clazz;
private Object object;

public Delegate(Class clazz, String methodName)
{
this.clazz = clazz;
this.methodName = methodName;
}

public Delegate(Object obj, String methodName)
{
this.object = obj;
this.methodName = methodName;
}

public void delegate(Object[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException
{
if (object != null) {
Class objClass = object.getClass();
Method method = objClass.getMethod(methodName, mapArgs(args));
method.invoke(object, args);
} else if (clazz != null) {
Method method = clazz.getDeclaredMethod(methodName, mapArgs(args));
if (Modifier.isStatic(method.getModifiers()))
method.invoke(null, args);
else
throw new NoSuchMethodException("Method "+method+" is not static on class "+clazz);
}
}

private final static Class[] mapArgs(Object[] args)
{
if (args != null) {
Class[] cArray = new Class[args.length];
for (int i=0;i<args.length;i++) {
if (args[i] != null)
cArray[i] = args[i].getClass();
else
cArray[i] = Object.class;
}
return cArray;
}
return null;
}

}

}

0 Comments:

Post a Comment

<< Home