代理
不改变源代码,对类增加新的功能。
/**
* 实现类,目标类
*/
public class WelcomeServiceImpl implements WS1,WS2 {
public void say1(String str) {
System.out.println("say1:" + str);
}
public void say2(String str, int age) {
System.out.println("say2:" + str + "," + age);
}
}
//
public class App {
public static void main(String[] args) {
//目标对象
WelcomeServiceImpl target = new WelcomeServiceImpl();
//处理器
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//计算时间
long start = System.nanoTime() ;
Object ret = method.invoke(target, args);
long duration = System.nanoTime() - start ;
System.out.println(method + ":" + args + " ===> " + duration);
return ret;
}
};
//接口列表
Class[] interfaces = {
WS1.class,
WS2.class
} ;
//代理对象
Object proxy = Proxy.newProxyInstance(App.class.getClassLoader(), interfaces, h);
//调用代理对象的方法。
((WS1)proxy).say1("tom");
((WS2)proxy).say2("tom",122);
}
}
1、定义接口
1 /** 2 * 定义接口 3 */ 4 public interface HelloWorldService { 5 public void sayHello(String str); 6 }
2、接口实现
public class HelloWorldServiceImpl implements HelloWorldService { public void sayHello(String str) { System.out.println(str); } }
3、实现测试
/** * 不改变源代码,还为类增加新功能。 * jdk的动态代理。 */ public class TestProxy { @Test public void test1(){ //目标对象 HelloWorldServiceImpl s = new HelloWorldServiceImpl(); //调用处理器 MyInvocationHandler h = new MyInvocationHandler(s); //接口列表 Class[] clazzes = {HelloWorldService.class}; //创建代理对象 HelloWorldService hws = (HelloWorldService) Proxy .newProxyInstance(HelloWorldServiceImpl.class.getClassLoader(), clazzes, h); //访问代理的方法. hws.sayHello("tom"); } //代理处理器 class MyInvocationHandler implements InvocationHandler{ //目标对象 private Object target ; public MyInvocationHandler(Object target){ this.target = target ; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("hello---world"); //调用目标对象的方法 return method.invoke(target, args); } } }