我尝试使用以下代码为给定的 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()]);
}
}
代理应该实现给定对象实现的所有接口(interface),并带有指示代理是否已创建的附加标记接口(interface)。 因为我不确定给定的对象是否直接实现 Runnable,所以我也在所有父类(super class)上遍历,但是我假设如果它实现另一个实现 Runnable 的接口(interface),它将起作用,所以我不需要也在接口(interface)层次结构上遍历.
但是,在尝试将代理转换为 Runnable
时,我仍然遇到 ClassCastException
:
java.lang.ClassCastException: $Proxy24 incompatible with java.lang.Runnable
我正在尝试思考什么可能导致此异常。给定对象的类层次结构不可用。
有什么想法吗?
最佳答案
更新删除了无用的代码。
这不是问题,但您应该使用 Set<Class<?>>
当您收集所有接口(interface)时,因为您可以在层次结构中获得相同接口(interface)的重复项。
关于java - 尝试创建代理对象时出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5622201/