2

我正在尝试使用以下代码为给定的 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

我正在尝试思考可能导致此异常的原因。给定对象的类层次结构不可用。

有任何想法吗 ?

4

2 回答 2

2

UPDATE删除了无用的代码。

这不是问题,但是Set<Class<?>>当您收集所有接口时应该使用 a,因为您可以在层次结构中获得相同接口的重复项。

于 2011-04-11T13:57:17.997 回答
1

你走超类的代码是错误的。代替

superClass = superClass.getClass().getSuperclass();

superClass = superClass.getSuperclass();

否则你会很快绕道去java.lang.Class,然后去java.lang.Object

于 2011-04-11T14:13:10.977 回答