1.动态代理
首先定义一个接口 Echo 接口中有一个方法echoBack()
public interface Echo {
public String echoBack(String message);
public String echoBack(String message1, String message2);
public String echoBack(String[] messages);
public int echoBack(int i);
public boolean echoBack(boolean b);
public void echo();
}
实现Echo 接口 EchoImpl
public class EchoImpl implements Echo {
public void echo() {
// TODO Auto-generated method stub
}
public boolean echoBack(boolean b) {
// TODO Auto-generated method stub
return b;
}
public int echoBack(int i) {
return i;
};
public String echoBack(String message) {
// TODO Auto-generated method stub
return message;
}
public String echoBack(String message1, String message2) {
// TODO Auto-generated method stub
return message1 + message2;
}
public String echoBack(String[] messages) {
// TODO Auto-generated method stub
final StringBuffer sb = new StringBuffer();
for (int i = 0; i < messages.length; i++) {
String message = messages[i];
sb.append(message);
}
System.out.println(sb);
return sb.toString();
}
}
测试类
public class CommonsProxyInterceptor {
private ProxyFactory factory;
private static final Class[] ECHO_ONLY = new Class[] { Echo.class };
public CommonsProxyInterceptor() {
this.factory = new ProxyFactory();
}
// 实现拦截器,过滤器
public void testMethodInvocationImplementation() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
final InterceptorTester tester = new InterceptorTester();
final EchoImpl target = new EchoImpl();
final Echo proxy = (Echo) factory.createInterceptorProxy(Class.forName("EchoImpl").newInstance(), tester, ECHO_ONLY);
proxy.echo();
proxy.echoBack(new String[] { "北京", "上海", "广州" });
proxy.echoBack("hello World!");
for (Object str : tester.getArguments())
System.out.println(str.toString());
target.equals(tester.getProxy());
}
// 实现动态代理
public void testMethodInvokerProxy() throws InstantiationException, IllegalAccessException {
final Echo proxy = (Echo) factory.createInvokerProxy(new InvokerTest(EchoImpl.class.newInstance()), ECHO_ONLY);
System.out.println(proxy.echoBack(new String[] { "北京", "上海", "广州"}));
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
CommonsProxyInterceptor proxy = new CommonsProxyInterceptor();
proxy.testMethodInvocationImplementation();
proxy.testMethodInvokerProxy();
}
}