package com.jason.pattern.proxy.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* 动态代理
* @author Administrator
*
*/
public class DynamicHandler implements InvocationHandler
{
private Object obj;// 代理的任何对象的引用
public DynamicHandler(Object obj)
{
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("before daynamic ......" + method);
method.invoke(obj, args);// args是方法中传递的参数
System.out.println("after daynamic ......" + method);
return null;
}
}
///
package com.jason.pattern.proxy.dynamic;
/**
* 动态代理
* @author Administrator
*
*/
public interface ISubject
{
void request();
}
//
package com.jason.pattern.proxy.dynamic;
public class RealSubject implements ISubject
{
@Override
public void request()
{
System.out.println("From real subject");
}
}
package com.jason.pattern.proxy.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
public class Client
{
/**
* @param args
*/
public static void main(String[] args)
{
RealSubject realSubject = new RealSubject();
InvocationHandler handler = new DynamicHandler(realSubject);
Class<?> classType = handler.getClass();
ISubject sub = (ISubject) Proxy.newProxyInstance(classType
.getClassLoader(), realSubject.getClass().getInterfaces(),
handler);
sub.request();
System.out.println(sub.getClass());
}
}
//下面看另外一个例子
package com.jason.pattern.proxy.dynamic;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Vector;
public class VectorProxy implements InvocationHandler
{
private Object object;
public VectorProxy(Object object)
{
this.object = object;
}
public static Object factory(Object obj)
{
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), new VectorProxy(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("before calling:" + method);
if (args != null)
{
for (Object obj : args)
System.out.println(obj);// 输出传递的参数
}
Object o = method.invoke(object, args);
System.out.println("after calling:" + method);
return o;
}
// test
public static void main(String[] args)
{
List v =(List) factory(new Vector());
v.add("Hello");
v.add("World");
System.out.println(v);
}
}
///输出:before calling:public abstract boolean java.util.List.add(java.lang.Object)
Hello
after calling:public abstract boolean java.util.List.add(java.lang.Object)
before calling:public abstract boolean java.util.List.add(java.lang.Object)
World
after calling:public abstract boolean java.util.List.add(java.lang.Object)
before calling:public java.lang.String java.lang.Object.toString()
after calling:public java.lang.String java.lang.Object.toString()
[Hello, World]