我正在尝试使用以下代码为给定的 Runnable 对象创建代理:
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()]);
}
}
代理应实现给定对象实现的所有接口,并带有指示代理是否已创建的附加标记接口。由于我不确定给定对象是否直接实现 Runnable 我也在所有超类上遍历,但是我假设如果它实现另一个实现 Runnable 的接口它将工作,所以我不需要遍历接口层次结构.
但是,ClassCastException
尝试将代理转换为Runnable
:
java.lang.ClassCastException: $Proxy24 incompatible with java.lang.Runnable
我正在尝试思考可能导致此异常的原因。给定对象的类层次结构不可用。
有任何想法吗 ?