接口HelloWorld
package lucas;
public interface HelloWorld {
public void sayHello();
}
接口实现类HelloWoldImpl
package lucas;
public class HelloWorldImpl implements HelloWorld {
@Override
public void sayHello() {
System.out.println("Hello World!");
}
}
动态代理绑定和代理逻辑实现:
package lucas;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyExample implements InvocationHandler {
private Object target = null;
/**
* 建立代理对象和真实对象之间的关系,并返回代理对象
* @param target : 真实对象
* @return 代理对象
*/
public Object bind(Object target) {
this.target = target;
/**
* target.getClass.getClassLoader(),target本身的类加载器
* target.getClass().getInterfaces(): 把生成的代理对象下挂到哪个接口下
* this:实现方法逻辑的代理类,this表示当前类,它必须实现InvocationHandler接口的invoke方法,invoke方法就是代理逻辑方法的实现方法
*/
Object o = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
return o;
}
/**
* 代理方法逻辑
* @param proxy :代理对象,就是bind方法生成的对象
* @param method : 当前调度的方法
* @param args: 当前方法参数
* @return 代理结果返回
* @throws Throwable
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("进入代理逻辑方法");
System.out.println("在调度真实对象之前的服务");
Object invoke = method.invoke(target, args);
System.out.println("在调度真实对象之后的服务");
return invoke;
}
}
测试类:
package lucas;
public class TestProxyExample {
public static void main(String[] args) {
/**
* 正常这样子
*/
HelloWorld helloWorld = new HelloWorldImpl();
helloWorld.sayHello();
/**
* JDK动态代理模式:
*/
JDKProxyExample jdkProxyExample = new JDKProxyExample();
HelloWorld hW = (HelloWorld) jdkProxyExample.bind(new HelloWorldImpl());
hW.sayHello();
}
}