1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.util;
17
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Proxy;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22
23 /**
24 * Proxy utility methods.
25 * @since Morph 1.1
26 *
27 * @author Matt Benson
28 */
29 public abstract class ProxyUtils {
30
31 /**
32 * Get a Proxy adding the specified interface to the specified object.
33 * @param object
34 * @param clazz
35 * @return Proxy
36 */
37 public static Proxy getProxy(Object object, Class clazz) {
38 return getProxy(object, clazz, new AnyAccessDelegatingInvocationHandler(object));
39 }
40
41 /**
42 * Get a Proxy adding the specified interface to the specified object.
43 * @param object
44 * @param clazz
45 * @param ih
46 * @return Proxy
47 */
48 public static Proxy getProxy(Object object, Class clazz, InvocationHandler ih) {
49 return getProxy(object, new Class[] { clazz }, ih);
50 }
51
52 /**
53 * Get a Proxy adding the specified interfaces to the specified object.
54 * @param object
55 * @param addInterfaces
56 * @param ih
57 * @return Proxy
58 */
59 public static Proxy getProxy(Object object, Class[] addInterfaces,
60 InvocationHandler ih) {
61 for (int i = 0; addInterfaces != null && i < addInterfaces.length; i++) {
62 if (!addInterfaces[i].isInterface()) {
63 throw new IllegalArgumentException(addInterfaces[i]
64 + " is not an interface");
65 }
66 }
67 ArrayList allInterfaces = new ArrayList(Arrays.asList(ClassUtils
68 .getInterfaces(object.getClass())));
69 for (int i = 0; i < addInterfaces.length; i++) {
70 if (!allInterfaces.contains(addInterfaces[i])) {
71 allInterfaces.add(addInterfaces[i]);
72 }
73 }
74 return (Proxy) Proxy.newProxyInstance(object.getClass().getClassLoader(),
75 (Class[]) allInterfaces.toArray(new Class[allInterfaces.size()]), ih);
76 }
77 }