ServiceInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, final Method m, Object[] params) throws Throwable { if (OBJECT_METHODS.contains(m)) { if (m.getName().equals("equals")) { params = new Object[] {Proxy.getInvocationHandler(params[0])}; } return m.invoke(this, params); } ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); final Object[] paramsFinal = params; return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return m.invoke(serviceObject, paramsFinal); } }); } catch (Throwable ex) { Throwable theCause = ex.getCause() == null ? ex : ex.getCause(); throw exceptionMapper.mapException(m, theCause); } finally { Thread.currentThread().setContextClassLoader(oldCl); } } ServiceInvocationHandler(Object serviceObject, Class<?> iType); @Override Object invoke(Object proxy, final Method m, Object[] params);  }
@Test public void testInvoke() throws Throwable { ServiceInvocationHandler sih = new ServiceInvocationHandler("hello", String.class); Method m = String.class.getMethod("length"); assertEquals(5, sih.invoke(null, m, new Object[] {})); }
@Test public void testInvokeObjectMethod() throws Throwable { final List<String> called = new ArrayList<>(); ServiceInvocationHandler sih = new ServiceInvocationHandler("hi", String.class) { @Override public boolean equals(Object obj) { called.add("equals"); return super.equals(obj); } @Override public int hashCode() { called.add("hashCode"); return super.hashCode(); } @Override public String toString() { called.add("toString"); return "somestring"; } }; Object proxy = Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] {Runnable.class}, sih); assertEquals(true, sih.invoke(null, OBJECT_METHODS.get("equals"), new Object[] {proxy})); assertEquals(System.identityHashCode(sih), sih.invoke(null, OBJECT_METHODS.get("hashCode"), new Object[] {})); assertEquals("somestring", sih.invoke(null, OBJECT_METHODS.get("toString"), new Object[] {})); assertEquals(Arrays.asList("equals", "hashCode", "toString"), called); }