需要被代理的
接口和类。注意:必须要定义接口。
class="java" name="code">package com.yan.proxy.object;
public interface ProxyObjectI {
public void sayHello();
}
被代理的类
package com.yan.proxy.object;
public class ProxyedObject implements ProxyObjectI{
@Override
public void sayHello() {
System.out.println("hello");
}
}
两个代理类authority log
package com.yan.proxy.object;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class AuthorityProxy implements InvocationHandler {
private Object proxy;
@Override
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
doBefore();
Object result = method.invoke(proxy, args);
doAfter();
return result;
}
public AuthorityProxy(Object proxy) {
this.proxy = proxy;
}
private void doBefore() {
System.out.println("before you are authoried! ");
}
private void doAfter() {
System.out.println("after you are authoried! ");
}
}
package com.yan.proxy.object;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogProxy implements InvocationHandler {
private Object proxy;
public LogProxy(Object proxy) {
this.proxy = proxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
doBefore();
Object result = method.invoke(this.proxy, args);
doAfter();
return result;
}
private void doBefore() {
System.out.println("before logging.............. ");
}
private void doAfter() {
System.out.println("after logging..............");
}
}
测试类
package com.yan.proxy.object;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
ProxyObjectI object = new ProxyedObject();
InvocationHandler authHandler = new AuthorityProxy(object);
ProxyObjectI authProxy = (ProxyObjectI) Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), authHandler);
InvocationHandler logHandler = new LogProxy(authProxy);
ProxyObjectI proxy = (ProxyObjectI) Proxy.newProxyInstance(authProxy.getClass().getClassLoader(), authProxy.getClass().getInterfaces(), logHandler);
proxy.sayHello();
}
}
输出结果:
before logging..............
before you are authoried!
hello
after you are authoried!
after logging..............
可以看到对象被一层一层的代理对象所封装。
- TestDynamicProxy.tar.gz (3.1 KB)
- 下载次数: 0