1 package com.thoughtworks.acceptance.objects; 2 3 import java.lang.reflect.InvocationHandler ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.Proxy ; 6 7 public class SampleDynamicProxy implements InvocationHandler { 8 9 private String aField = "hello"; 10 11 public static interface InterfaceOne { 12 String doSomething(); 13 } 14 15 public static interface InterfaceTwo { 16 String doSomething(); 17 } 18 19 public static Object newInstance() { 20 return Proxy.newProxyInstance(InterfaceOne.class.getClassLoader(), 21 new Class []{InterfaceOne.class, InterfaceTwo.class}, 22 new SampleDynamicProxy()); 23 } 24 25 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 26 if (method.getName().equals("equals")) { 27 return equals(args[0]) ? Boolean.TRUE : Boolean.FALSE; 28 } else { 29 return aField; 30 } 31 } 32 33 public boolean equals(Object obj) { 34 return equalsInterfaceOne(obj) && equalsInterfaceTwo(obj); 35 } 36 37 private boolean equalsInterfaceOne(Object o) { 38 if (o instanceof InterfaceOne) { 39 InterfaceOne interfaceOne = (InterfaceOne) o; 40 return aField.equals(interfaceOne.doSomething()); 41 } else { 42 return false; 43 } 44 } 45 46 private boolean equalsInterfaceTwo(Object o) { 47 if (o instanceof InterfaceTwo) { 48 InterfaceTwo interfaceTwo = (InterfaceTwo) o; 49 return aField.equals(interfaceTwo.doSomething()); 50 } else { 51 return false; 52 } 53 } 54 55 } 56 | Popular Tags |