import java.lang.reflect.InvocationHandler;
import
java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import junit.framework.TestCase;
/**
* @author Ed Sumerfield
*/
public class
DynamicProxyTest extends TestCase
{
private
ProxyTestInterface m_proxy;
/* (non-Javadoc)
* @see
junit.framework.TestCase#setUp()
*/
protected void setUp() throws
Exception
{
ProxyTestImpl impl = new
ProxyTestImpl();
Class[]
arguments = new Class[] { ProxyTestInterface.class
};
InvocationHandler proxyImpl =
new ProxyTestProxy(impl);
m_proxy =
(ProxyTestInterface)Proxy.newProxyInstance(impl.getClass()
.getClassLoader(), arguments, proxyImpl);
}
/**
* Prove that we can call
a proxy method
*/
public
void testCallProxyMethod()
{
m_proxy.aMethod();
}
/**
* Prove that we can call
a proxy method and pass in an argument
*/
public void
testCallProxyMethodWithArgs()
{
m_proxy.aMethodWithArgs("hello
world");
}
/**
* Prove that an
exception can be thrown from the delegate.
*
@throws Exception
*/
public
void testThrowException() throws Throwable
{
try
{
m_proxy.aMethodWithAnException();
fail("Should have thrown
exception");
}
catch (ProxyTestException
e)
{
//
Success
}
}
}
interface ProxyTestInterface
{
public void
aMethod();
public void aMethodWithArgs(String
a_text);
public void aMethodWithAnException() throws
ProxyTestException;
}
class ProxyTestImpl implements
ProxyTestInterface
{
public void
aMethod()
{
System.out.println("aMethod
called");
}
public void aMethodWithArgs(String
a_text)
{
System.out.println("aMethodWithArgs called: " + a_text);
}
public void aMethodWithAnException() throws
ProxyTestException
{
System.out.println("aMethodWithAnException
called");
throw new
ProxyTestException();
}
}
class ProxyTestProxy implements
InvocationHandler
{
private ProxyTestInterface
m_impl;
public ProxyTestProxy(ProxyTestInterface
a_impl)
{
m_impl = a_impl;
}
public Object invoke(Object a_proxy, Method a_method,
Object[]
a_args)
throws Throwable
{
System.out.println("Proxy
calling: " +
a_method.getName());
return
a_method.invoke(m_impl, a_args);
}
}
class ProxyTestException extends Exception
{
}