동적 프록시(Dynamic Proxy)
1969 단어 dynamic proxy
package com.test;
/**
*
* @author yale
*
*/
public interface ISubject
{
public void request();
}
package com.test;
/**
*
* @author yale
*
*/
public class RealSubject implements ISubject
{
public void request()
{
System.out.println("real subject request");
}
}
package com.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* , InvocationHandler
* @author yale
*
*/
public class DynamicSubject implements InvocationHandler
{
private Object obj;//
public DynamicSubject(Object o)
{
this.obj = o;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println("before request");
method.invoke(obj,args);
System.out.println("after request");
return null;
}
}
package com.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
*
*
* @author yale
*
*/
public class Client
{
public static void main(String[] args)
{
RealSubject realSubject = new RealSubject();
InvocationHandler handler = new DynamicSubject(realSubject);
Class<?> classType = handler.getClass();
ISubject subject = (ISubject) Proxy.newProxyInstance(classType
.getClassLoader(), realSubject.getClass().getInterfaces(),
handler);
subject.request();
}
}