List of usage examples for java.lang.reflect InvocationHandler InvocationHandler
InvocationHandler
From source file:therian.util.ReadOnlyUtils.java
public static <T> Deque<T> wrap(Deque<T> deque) { @SuppressWarnings("unchecked") final Deque<T> result = (Deque<T>) Proxy.newProxyInstance( Validate.notNull(deque, "object required to wrap").getClass().getClassLoader(), new Class[] { Deque.class }, new InvocationHandler() { public Object invoke(Object o, Method method, Object[] objects) throws Throwable { if (StringUtils.startsWithAny(method.getName(), "add", "offer", "poll", "pop", "push", "remove", "clear", "retain")) { throw new UnsupportedOperationException("read-only"); }//from w w w .j a v a 2 s .c om final Object result = method.invoke(o, objects); if (StringUtils.endsWithIgnoreCase(method.getName(), "iterator")) { final Iterator<?> wrapIterator = (Iterator<?>) result; return new Iterator<Object>() { public boolean hasNext() { return wrapIterator.hasNext(); } public Object next() { return wrapIterator.next(); } public void remove() { } }; } return null; } }); return result; }
From source file:org.mule.module.magento.api.MagentoClientAdaptor.java
@SuppressWarnings("unchecked") public static <T> T adapt(final Class<T> receptorClass, final T receptor) { Validate.isTrue(receptorClass.isInterface()); return (T) Proxy.newProxyInstance(MagentoClientAdaptor.class.getClassLoader(), new Class[] { receptorClass }, new InvocationHandler() { public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { try { if (log.isDebugEnabled()) { log.debug("Entering {} with args {}", method.getName(), args); }// ww w . j a v a 2 s . co m final Object ret = method.invoke(receptor, args); if (log.isDebugEnabled()) { log.debug("Returning from {} with value {}", method.getName(), ret); } return ret; } catch (final InvocationTargetException e) { if (e.getCause() instanceof AxisFault) { if (log.isWarnEnabled()) { log.warn("An exception was thrown while invoking {}: {}", method.getName(), e.getCause()); } throw toMagentoException((AxisFault) e.getCause()); } throw e; } } }); }
From source file:com.almende.eve.agent.AgentProxyFactory.java
/** * Gen proxy.//from www . j a va 2s . c om * * @param <T> * the generic type * @param sender * the sender * @param receiverUrl * the receiver url * @param proxyInterface * the interface this proxy implements * @return the t */ @SuppressWarnings("unchecked") public static <T> T genProxy(final Agent sender, final URI receiverUrl, final Class<T> proxyInterface) { // http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html final T proxy = (T) Proxy.newProxyInstance(proxyInterface.getClassLoader(), new Class[] { proxyInterface }, new InvocationHandler() { private Map<Method, Boolean> cache = new HashMap<Method, Boolean>(); @Override public Object invoke(final Object proxy, final Method method, final Object[] args) { boolean doSync = true; if (cache.containsKey(method)) { doSync = cache.get(method); } else { AnnotatedClass clazz = AnnotationUtil.get(proxyInterface); if (clazz != null) { List<AnnotatedMethod> list = clazz.getMethods(method.getName()); for (AnnotatedMethod m : list) { if (m.getAnnotation(NoReply.class) != null) { doSync = false; } } if (doSync && method.getReturnType().equals(void.class) && clazz.getAnnotation(NoReply.class) != null) { doSync = false; } } cache.put(method, doSync); } SyncCallback<JsonNode> callback = null; if (doSync) { callback = new SyncCallback<JsonNode>() { }; } try { sender.call(receiverUrl, method, args, callback); } catch (final IOException e) { throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e); } if (callback != null) { try { return TypeUtil.inject(callback.get(), method.getGenericReturnType()); } catch (final Exception e) { throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e); } } return null; } }); return proxy; }
From source file:com.netflix.iep.config.Configuration.java
@SuppressWarnings("unchecked") public static <T> T newProxy(final Class<T> ctype, final String prefix) { InvocationHandler handler = new InvocationHandler() { @Override//from w ww . j a v a2s . co m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("get")) { return iConfiguration.get((args[0] == null) ? null : args[0].toString()); } else { Class rt = method.getReturnType(); String key = (prefix == null) ? method.getName() : prefix + "." + method.getName(); if (IConfiguration.class.isAssignableFrom(rt)) { return newProxy(rt, key); } else { String value = iConfiguration.get(key); if (value == null) { DefaultValue anno = method.getAnnotation(DefaultValue.class); value = (anno == null) ? null : anno.value(); } if (value == null) { if (rt.isPrimitive()) throw new IllegalStateException("no value for property " + method.getName()); return null; } return Strings.cast(rt, value); } } } }; return (T) Proxy.newProxyInstance(ctype.getClassLoader(), new Class[] { ctype }, handler); }
From source file:io.lavagna.common.QueryFactory.java
@SuppressWarnings("unchecked") private static <T> T from(final Class<T> clazz, final String activeDb, final NamedParameterJdbcTemplate jdbc) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() { @Override// ww w .j a va 2 s . c o m public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { QueryTypeAndQuery qs = extractQueryAnnotation(clazz, activeDb, method); return qs.type.apply(qs.query, jdbc, method, args); } }); }
From source file:ProxyAdapter.java
@SuppressWarnings("unchecked") public ProxyAdapter(Class... interfaces) { proxy = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Method m;//from w w w .j a v a2 s . com try { //Determine if the method has been defined in a subclass m = ProxyAdapter.this.getClass().getMethod(method.getName(), method.getParameterTypes()); m.setAccessible(true); } catch (Exception e) { //if not found throw new UnsupportedOperationException(method.toString(), e); } //Invoke the method found and return the result try { return m.invoke(ProxyAdapter.this, args); } catch (InvocationTargetException e) { throw e.getCause(); } } }); }
From source file:Main.java
/** * Wraps an {@link ExecutorService} in such a way as to "protect" * it for calls to the {@link ExecutorService#shutdown()} or * {@link ExecutorService#shutdownNow()}. All other calls are delegated as-is * to the original service. <B>Note:</B> the exposed wrapped proxy will * answer correctly the {@link ExecutorService#isShutdown()} query if indeed * one of the {@code shutdown} methods was invoked. * * @param executorService The original service - ignored if {@code null} * @param shutdownOnExit If {@code true} then it is OK to shutdown the executor * so no wrapping takes place. * @return Either the original service or a wrapped one - depending on the * value of the <tt>shutdownOnExit</tt> parameter *//* w w w . j av a 2 s . c o m*/ public static ExecutorService protectExecutorServiceShutdown(final ExecutorService executorService, boolean shutdownOnExit) { if (executorService == null || shutdownOnExit) { return executorService; } else { return (ExecutorService) Proxy.newProxyInstance(resolveDefaultClassLoader(executorService), new Class<?>[] { ExecutorService.class }, new InvocationHandler() { private final AtomicBoolean stopped = new AtomicBoolean(false); @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); if ("isShutdown".equals(name)) { return stopped.get(); } else if ("shutdown".equals(name)) { stopped.set(true); return null; // void... } else if ("shutdownNow".equals(name)) { stopped.set(true); return Collections.emptyList(); } else { return method.invoke(executorService, args); } } }); } }
From source file:ch.sourcepond.maven.release.providers.BaseProvider.java
@SuppressWarnings("unchecked") @Override/*from w w w. ja v a2s .c om*/ public T get() { return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { getDelegateType() }, new InvocationHandler() { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { notNull(getDelegate(), "Delegate object is not available!"); try { return method.invoke(getDelegate(), args); } catch (final InvocationTargetException e) { throw e.getTargetException(); } } }); }
From source file:org.springframework.validation.ExtendedValidationUtils.java
/** * @param validator The {@link TypedValidator} * @param cl The {@link ClassLoader} to use for the proxy * @return A proxy {@link Validator} that delegates the calls to the typed one *//*from ww w. jav a2 s .c o m*/ public static final <E> Validator toValidator(final TypedValidator<E> validator, ClassLoader cl) { Assert.notNull(validator, "No validator instance"); Assert.notNull(cl, "No class loader"); return ProxyUtils.newProxyInstance(Validator.class, cl, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (SUPPORTS_METHOD_SIGNATURE.evaluate(method)) { Class<E> expected = validator.getEntityClass(); Class<?> actual = (Class<?>) args[0]; return Boolean.valueOf(expected.isAssignableFrom(actual)); } else if (VALIDATE_METHOD_SIGNATURE.evaluate(method)) { Class<E> expected = validator.getEntityClass(); validator.validate(expected.cast(args[0]), (Errors) args[1]); return null; } else { return method.invoke(validator, args); } } }, Validator.class); }
From source file:org.apache.servicemix.nmr.spring.BundleExtTest.java
public void test() { final long bundleId = 32; BundleExtUrlPostProcessor processor = new BundleExtUrlPostProcessor(); processor.setBundleContext((BundleContext) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { BundleContext.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getBundle".equals(method.getName())) { return (Bundle) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { Bundle.class }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("getBundleId".equals(method.getName())) { return bundleId; } return null; }//from w ww .j a va 2s . c o m }); } return null; //To change body of implemented methods use File | Settings | File Templates. } })); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "bundle.xml" }, false); ctx.addBeanFactoryPostProcessor(processor); ctx.refresh(); Object str = ctx.getBean("string"); System.err.println(str); assertNotNull(str); assertEquals("bundle://" + bundleId + "///schema.xsd", str); }