View Javadoc

1   /*
2    * Copyright 2004-2005, 2007 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.composite.util;
17  
18  import java.lang.reflect.InvocationHandler;
19  import java.lang.reflect.InvocationTargetException;
20  import java.lang.reflect.Method;
21  
22  /***
23   * An invocation handler that delegates method calls to a delegate object.  This
24   * invocation handler is useful for declaring that a class implements a given
25   * interface at runtime rather than at compile time.  The delegate object must
26   * already have implementations for each method declared in the interface.
27   * 
28   * @author Matt Sgarlata
29   * @since Dec 27, 2004
30   */
31  public class DelegatingInvocationHandler implements InvocationHandler {
32  
33  	private Object delegate;
34  
35  	/***
36  	 * Creates a new invocation handler that delegates invocation requests to
37  	 * the specified delegate.
38  	 * 
39  	 * @param delegate
40  	 *            the delegate that will be used
41  	 */
42  	public DelegatingInvocationHandler(Object delegate) {
43  		super();
44  		setDelegate(delegate);
45  	}
46  
47  	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
48  		try {
49  			Object delegateToUse = getDelegate(proxy, method, args);
50  			Method delegateMethod = getDelegateMethod(delegateToUse, method, args);
51  			return delegateMethod.invoke(delegateToUse, args);
52  		}
53  		// if an exception is thrown by the invoke method, just rethrow it
54  		// without it wrapped in an InvocationTargetException 
55  		catch (InvocationTargetException e) {
56  			throw e.getTargetException();
57  		}
58  	}
59  
60  	protected Method getDelegateMethod(Object delegate, Method method, Object[] args)
61  			throws Exception {
62  		return delegate.getClass().getMethod(method.getName(), method.getParameterTypes());
63  	}
64  
65  	protected Object getDelegate(Object proxy, Method method, Object[] args) {
66  		return getDelegate();
67  	}
68  
69  	public Object getDelegate() {
70  		return delegate;
71  	}
72  
73  	public void setDelegate(Object delegate) {
74  		this.delegate = delegate;
75  	}
76  
77  }