动态代理

public class JavaMain {

    public static void main(String[] args) {
        BBA bba = new BBA();
        ICar proxy = (ICar)Proxy.newProxyInstance(bba.getClass().getClassLoader(), 
        bba.getClass().getInterfaces(), 
        new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                if("drive".equals(methodName)){
                    System.out.println("Dynamic Proxy start....");
                    method.invoke(bba, args);
                    System.out.println("Dynamic Proxy end....");
                }
                return null;
            }
        });
        proxy.drive();
    }

}

总结:使用动态代理,用来生成代理的委托对象必须是一个接口,如果不是接口将会报错:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to ***

results matching ""

    No results matching ""