jdk1.3引入的动态代理号称可以在运行时实现多个接口。但我发觉这是假的,譬如我有一个类,Donkey(驴子),我现在要把它变成飞马,当然是在运行时。那么我想动态的让他实现CanRun接口和CanFly接口,结果做不到,除非Donkey类编译时就声明implements CanFly, CanRun。是这样吗?

解决方案 »

  1.   

    写个例子import java.lang.reflect.*;
    import java.util.*;interface CanFly
    {
    void fly(String name, int value);
    }interface CanRun
    {
    void run(String name, int value);
    }public class ProxyTest
    {
    public static void testCanFly(CanFly fly)
    {
    fly.fly("hello", 3);
    } public static void testCanRun(CanRun run)
    {
    run.run("world", 5);
    } public static void main(String[] args)
    {
    InvocationHandler h = new Donkey();
    Object proxy = Proxy.newProxyInstance(CanFly.class.getClassLoader(), 
    new Class[]{ CanFly.class, CanRun.class }, h);

    testCanFly((CanFly)proxy);
    testCanRun((CanRun)proxy);
    }
    }class Donkey implements InvocationHandler
    {
    public Object invoke(Object proxy, Method m, Object[] args)
    {
    System.out.print("Method name: " + m.getName() + "("); if (args != null)
    {
    for (int i = 0; i < args.length; i++)
    {
    System.out.print(args[i]);
    if (i < args.length - 1)
    {
    System.out.print(", ");
    }
    }
    } System.out.println(")"); return null;
    }
    };
      

  2.   

    没有问题呀,JDK代理只代理接口
    什么叫实现接口:就是implements 了某个接口
    而不是说你写了一个和接口同名的方法就实现了接口