View Javadoc

1   /*
2    * Copyright 2007-2008 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
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  }