I'm trying to create a proxy for a given Runnable object using the following code:
public class WorkInvocationHandler implements InvocationHandler {
public static Runnable newProxyInstance(Runnable work)
{
return (Runnable)java.lang.reflect.Proxy.newProxyInstance(
work.getClass().getClassLoader(),
getInterfacesWithMarker(work),
new WorkInvocationHandler(work));
}
private static Class[] getInterfacesWithMarker(Runnable work)
{
List allInterfaces = new ArrayList();
// add direct interfaces
allInterfaces.addAll(Arrays.asList(work.getClass().getInterfaces()));
// add interfaces of super classes
Class superClass = work.getClass().getSuperclass();
while (!superClass.equals(Object.class))
{
allInterfaces.addAll(Arrays.asList(superClass.getInterfaces()));
superClass = superClass.getClass().getSuperclass();
}
// add marker interface
allInterfaces.add(IWorkProxy.class);
return (Class [])allInterfaces.toArray(new Class[allInterfaces.size()]);
}
}
The proxy should implement all interfaces that the given object implements with the additional marker interface that indicates whether the proxy was already created. Since I don't know for sure that the given object implements Runnable directly I traverse also on all super classes, however I assume that if it implements another interface that implements Runnable it will work so I don't need to traverse also on interfaces hierarchy.
However, I still get ClassCastException when trying to cast the proxy to Runnable:
java.lang.ClassCastException: $Proxy24 incompatible with java.lang.Runnable
I'm trying to think what could cause this exception. The class hierarchy of the given object is not available.
Any ideas ?
newProxyInstance()(i.e.Arrayconstructed in place) and see if it works.