import junit.framework.TestCase;
import junit.framework.Assert;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationHandler;
public class DynamicProxyTest extends TestCase {
private Object proxy;
public void setUp() throws Exception
{
proxy = makeAProxyWhichExtendsTestInterface();
}
private Object makeAProxyWhichExtendsTestInterface()
{
return Proxy.newProxyInstance(TestInterface.class.getClassLoader(), new Class[]{TestInterface.class},new TestInvocationHandler());
}
private class TestInvocationHandler implements InvocationHandler
{
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable
{
if ("operationA".equals(method.getName()))
{
System.out.println("operationA in proxy");
}
else if ("operationB".equals(method.getName()))
{
System.out.println("operationB in proxy");
}
else if ("equals".equals(method.getName()))
{
return true;
}
else if ("hashCode".equals(method.getName()))
{
return 100;
}
else if ("toString".equals(method.getName())){
return "proxy.toString()";
}
return null;
}
}
public void testProxyDoesExtendTheInterface ()
{
Assert.assertTrue(proxy instanceof TestInterface);
}
public void testProxyClassIsPublicAndFinalButNotAbstract ()
{
Assert.assertTrue(Modifier.isPublic(proxy.getClass().getModifiers()));
Assert.assertTrue(Modifier.isFinal(proxy.getClass().getModifiers()));
Assert.assertFalse(Modifier.isAbstract(proxy.getClass().getModifiers()));
}
public void testProxyInheritedFromJavaLangReflectProxy ()
{
Assert.assertSame(java.lang.reflect.Proxy.class,proxy.getClass().getSuperclass());
}
public void testUnqualifiedNameOfProxyStartsWith $Proxy()
{
Assert.assertTrue(proxy.getClass().getSimpleName().startsWith("$Proxy"));
}
public void testToStringOfProxyIsHandledByInvocationHandler ()
{
Assert.assertEquals("proxy.toString()",proxy.toString());
}
public void testEqualsOfProxyIsHandledByInvocationHandler ()
{
Assert.assertEquals(proxy,makeAProxyWhichExtendsTestInterface());
Assert.assertEquals(proxy,null);
}
public void testhashCodeOfProxyIsHandledByInvocationHandler ()
{
Assert.assertEquals(100,proxy.hashCode());
Assert.assertEquals(100,makeAProxyWhichExtendsTestInterface().hashCode()); }
public interface TestInterface
{
void operationA();
void operationB();
}
}
Dynamic Proxy
最新推荐文章于 2024-07-17 21:08:54 发布