Java知识123

Java 动态代理

2017-06-20  本文已影响4人  奔跑的笨鸟

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

可见Java的动态代理是基于Interface的。Spring AOP 功能就是利用的Java动态代理。

动态代理的用处:

实现动态代理的要点:

一个例子:

package ttttt;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.management.RuntimeErrorException;

interface SomeInterface {
    public void doSomething();
}

class SomeImpl implements SomeInterface {

    @Override
    public void doSomething() {
        System.out.println("I am working!");

    }

}

class SomeProxy implements InvocationHandler {
    private SomeInterface SomeImpl;

    public SomeProxy(SomeInterface someImpl) {
        super();
        SomeImpl = someImpl;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("proxy class is " + proxy.getClass().getCanonicalName());
        System.out.println("Do something before.");
        Object object = method.invoke(SomeImpl, args);
        System.out.println("do something after.");
        return object;
    }

}

public class ProxyTest {
    public static void main(String[] args) {
        SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(SomeInterface.class.getClassLoader(),
                new Class[] { SomeInterface.class }, new SomeProxy(new SomeImpl()));
        proxy.doSomething();

    }

}

执行结果:

proxy class is ttttt.$Proxy0
Do something before.
I am working!
do something after.

参考:
Dynamic Proxy Classes
Java的动态代理(dynamic proxy)

上一篇 下一篇

猜你喜欢

热点阅读