KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > common > proxy > DelegatingInvocationHandler


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.common.proxy;
5
6 import com.tc.logging.TCLogger;
7 import com.tc.logging.TCLogging;
8 import com.tc.util.Assert;
9
10 import java.lang.reflect.InvocationTargetException JavaDoc;
11 import java.lang.reflect.Method JavaDoc;
12
13 /**
14  * @author andrew A {@link GenericInvocationHandler}that delegates all unknown methods to a special 'delegate' object.
15  * This is very useful for creating delegates that override only certain methods.
16  */

17 class DelegatingInvocationHandler extends GenericInvocationHandler {
18   private static final TCLogger logger = TCLogging.getLogger(GenericInvocationHandler.class);
19   private final Object JavaDoc delegate;
20
21   public DelegatingInvocationHandler(Object JavaDoc delegate, Object JavaDoc handler) {
22     super(handler);
23     Assert.eval(delegate != null);
24     this.delegate = delegate;
25   }
26
27   protected Object JavaDoc handlerMethodNotFound(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc {
28     try {
29       Method JavaDoc theMethod = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());
30
31       try {
32         theMethod.setAccessible(true);
33       } catch (SecurityException JavaDoc se) {
34         logger.warn("Cannot setAccessible(true) for method [" + theMethod + "], " + se.getMessage());
35       }
36
37       return theMethod.invoke(delegate, args);
38     } catch (InvocationTargetException JavaDoc ite) {
39       // We need to unwrap this; we want to throw what the method actually
40
// threw, not an InvocationTargetException (which causes all sorts of
41
// madness, since it's unlikely the interface method throws that
42
// exception, and you'll end up with an UndeclaredThrowableException.
43
// Blech.)
44
throw ite.getCause();
45     } catch (NoSuchMethodException JavaDoc nsme) {
46       return super.handlerMethodNotFound(proxy, method, args);
47     }
48   }
49 }
Popular Tags