先看静态代理的代码:
package com.reflect;
public interface HelloWorld {
public void sayHi();
}
package com.reflect;
public class HelloWorldImpl implements HelloWorld {
@Override
public void sayHi() {
System.out.println("Hi");
}
}
package com.reflect;
public class HelloWorldStaticProxy implements HelloWorld {
private HelloWorld helloWorld;
public HelloWorldStaticProxy(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}
@Override
public void sayHi() {
helloWorld.sayHi();
}
}
package com.reflect;
public interface Welcome {
public void welcome();
}
package com.reflect;
public class WelcomeImpl implements Welcome {
@Override
public void welcome() {
System.out.println("welcome");
}
}
package com.reflect;
public class WelcomeStaticProxy implements Welcome {
private Welcome welcome;
public WelcomeStaticProxy(Welcome welcome) {
this.welcome = welcome;
}
@Override
public void welcome() {
welcome.welcome();
}
}
测试代码
package com.reflect;
import junit.framework.TestCase;
public class TestProxy extends TestCase {
public void testStaticProxy() {
HelloWorld helloWorld = new HelloWorldStaticProxy(new HelloWorldImpl());
helloWorld.sayHi();
Welcome welcomeProxy = new WelcomeStaticProxy(new WelcomeImpl());
welcomeProxy.welcome();
}
public void testDynamicProxy() {
HelloWorldInvocationHandler handler = new HelloWorldInvocationHandler();
HelloWorld helloWorld = (HelloWorld) handler.bind(new HelloWorldImpl());
helloWorld.sayHi();
Welcome welcome = (Welcome) handler.bind(new WelcomeImpl());
welcome.welcome();
}
}
测试一下静态代理
运行testStaticProxy,输出:
Hi
welcome
看看代码,发现一个静态代理类对应一个接口,有多少个接口,就需要多少个静态代理类。
现在看动态代理的代码:
package com.reflect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloWorldInvocationHandler implements InvocationHandler {
private Object target;
public Object bind(Object target) {
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(target, args);
}
}
运行testDynamicProxy:
输出
Hi
welcome
看到代码,一个动态代理类,可以对应多个接口,因为参数是Object。这样,多个接口,只要一个代理类就行了。