Example usage for java.lang.reflect Proxy isProxyClass

List of usage examples for java.lang.reflect Proxy isProxyClass

Introduction

In this page you can find the example usage for java.lang.reflect Proxy isProxyClass.

Prototype

public static boolean isProxyClass(Class<?> cl) 

Source Link

Document

Returns true if the given class is a proxy class.

Usage

From source file:org.apache.hadoop.hbase.client.coprocessor.Batch.java

/**
 * Creates a new {@link Batch.Call} instance that invokes a method
 * with the given parameters and returns the result.
 *
 * @param method the method reference to invoke
 * @param args zero or more arguments to be passed to the method
 * @param <T> the class type of the protocol implementation being invoked
 * @param <R> the return type for the method call
 * @return a {@code Callable} instance that will invoke the given method and
 * return the results/* ww  w . j a v a2s  .c  o m*/
 * @see org.apache.hadoop.hbase.client.HTable#coprocessorExec(Class, byte[], byte[], org.apache.hadoop.hbase.client.coprocessor.Batch.Call, org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)
 */
public static <T extends CoprocessorProtocol, R> Call<T, R> forMethod(final Method method,
        final Object... args) {
    return new Call<T, R>() {
        public R call(T instance) throws IOException {
            try {
                if (Proxy.isProxyClass(instance.getClass())) {
                    InvocationHandler invoker = Proxy.getInvocationHandler(instance);
                    return (R) invoker.invoke(instance, method, args);
                } else {
                    LOG.warn("Non proxied invocation of method '" + method.getName() + "'!");
                    return (R) method.invoke(instance, args);
                }
            } catch (IllegalAccessException iae) {
                throw new IOException("Unable to invoke method '" + method.getName() + "'", iae);
            } catch (InvocationTargetException ite) {
                throw new IOException(ite.toString(), ite);
            } catch (Throwable t) {
                throw new IOException(t.toString(), t);
            }
        }
    };
}

From source file:com.googlecode.jsonrpc4j.JsonRpcMultiServer.java

/**
 * Returns the handler's class or interfaces.  The serviceName is used
 * to look up a registered handler.// w  w w .j  a v a2s.  c  om
 *
 * @param serviceName the optional name of a service
 * @return the class
 */
@Override
protected Class<?>[] getHandlerInterfaces(String serviceName) {
    Class<?> remoteInterface = interfaceMap.get(serviceName);
    if (remoteInterface != null) {
        return new Class<?>[] { remoteInterface };
    } else if (Proxy.isProxyClass(getHandler(serviceName).getClass())) {
        return getHandler(serviceName).getClass().getInterfaces();
    } else {
        return new Class<?>[] { getHandler(serviceName).getClass() };
    }
}

From source file:com.hubspot.utils.circuitbreaker.CircuitBreakerWrapper.java

/**
 * Ensures that the object we're wrapping and it's base interface conform to our restrictions
 * @throws CircuitBreakerWrappingException
 *//*from w ww . j a va2 s  . c  o  m*/
private <T, W extends T> void sanityCheck(W toWrap, Class<T> interfaceToProxy, CircuitBreakerPolicy policy)
        throws CircuitBreakerWrappingException {
    if (toWrap == null) {
        throw new CircuitBreakerWrappingException("Cannot wrap a null object");
    }
    if (interfaceToProxy == null) {
        throw new CircuitBreakerWrappingException("Cannot proxy a null interface");
    }
    if (!interfaceToProxy.isInterface()) {
        throw new CircuitBreakerWrappingException("interfaceToProxy must be an interface");
    }

    try {
        if (Proxy.isProxyClass(toWrap.getClass())
                && Proxy.getInvocationHandler(toWrap) instanceof CircuitBreakerInvocationHandler) {
            throw new CircuitBreakerWrappingException("Object is already wrapped in a circuit breaker.");
        }
    } catch (IllegalArgumentException ex) {
        // "this should never happen", but if it does, we'll log our own logic error
        // before throwing the bad wrap
        getLog().error("IllegalArgumentException when trying to check for previous wrap", ex);
        throw new CircuitBreakerWrappingException("Trouble detecting whether object was already proxied");
    }
}

From source file:com.lambdaworks.redis.RedisConnectionPool.java

private PooledObjectFactory<T> createFactory(final RedisConnectionProvider<T> redisConnectionProvider) {
    return new BasePooledObjectFactory<T>() {

        @SuppressWarnings("unchecked")
        @Override/*from   ww w.  ja  va 2  s .  c o m*/
        public T create() throws Exception {

            T connection = redisConnectionProvider.createConnection();
            PooledConnectionInvocationHandler<T> h = new PooledConnectionInvocationHandler<>(connection,
                    RedisConnectionPool.this);

            Object proxy = Proxy.newProxyInstance(getClass().getClassLoader(),
                    new Class<?>[] { redisConnectionProvider.getComponentType() }, h);

            return (T) proxy;
        }

        @Override
        public PooledObject<T> wrap(T obj) {
            return new DefaultPooledObject<>(obj);
        }

        @Override
        public boolean validateObject(PooledObject<T> p) {
            return Connections.isOpen(p.getObject());
        }

        @Override
        @SuppressWarnings("unchecked")
        public void destroyObject(PooledObject<T> p) throws Exception {

            T object = p.getObject();
            if (Proxy.isProxyClass(object.getClass())) {
                PooledConnectionInvocationHandler<T> invocationHandler = (PooledConnectionInvocationHandler<T>) Proxy
                        .getInvocationHandler(object);

                object = invocationHandler.getConnection();
            }

            Connections.close(object);
        }
    };
}

From source file:org.springframework.jdbc.core.JdbcOperationsUtils.java

public static final void validatePropertyValue(String id, String propName, Object propValue,
        ConversionService converter) {//from   w ww. j a  v a2  s .com
    if (StringUtils.isEmpty(propName)) {
        throw new IllegalStateException("validatePropertyValue(" + id + ") no property name");
    }

    if (propValue == null) {
        throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "] no value");
    }

    if (!(propValue instanceof Serializable)) {
        throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "] not serializable");
    }

    Class<?> propType = resolveEffectivePropertyType(propValue);
    if (Date.class.isAssignableFrom(propType) || Calendar.class.isAssignableFrom(propType)) {
        return; // Date(s) have a special handling
    }

    if (propType == Class.class) {
        Class<?> valueClass = (Class<?>) propValue;
        if (Proxy.isProxyClass(valueClass)) {
            throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "] proxies N/A");
        }

        if (valueClass.isAnonymousClass()) {
            throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "]"
                    + " anonymous classes N/A: " + valueClass.getName());
        }

        if (valueClass.isLocalClass()) {
            throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "]"
                    + " local classes N/A: " + valueClass.getName());
        }

        if (valueClass.isArray()) {
            throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "]"
                    + " array classes N/A: " + valueClass.getName());
        }

        int mods = valueClass.getModifiers();
        if (!Modifier.isPublic(mods)) {
            throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "]"
                    + " non-public classes N/A: " + valueClass.getName());
        }
    }

    if (!converter.canConvert(String.class, propType)) {
        throw new IllegalStateException("validatePropertyValue(" + id + ")[" + propName + "]"
                + " cannot convert a string to a " + propType.getSimpleName());
    }
}

From source file:com.opensymphony.xwork2.util.ProxyUtil.java

/**
 * Check whether the given object is a Spring proxy.
 * @param object the object to check//  w  w w  .  j a  v  a 2s.  c  o m
 */
private static boolean isSpringAopProxy(Object object) {
    Class<?> clazz = object.getClass();
    return (implementsInterface(clazz, SPRING_SPRINGPROXY_CLASS_NAME)
            && (Proxy.isProxyClass(clazz) || isCglibProxyClass(clazz)));
}

From source file:com.gs.jrpip.client.FastServletProxyInvocationHandler.java

/**
 * Handles the object invocation.//from   ww w .j  a  v a2 s .  c om
 *
 * @param proxy  the proxy object to invoke
 * @param method the method to call
 * @param args   the arguments to the proxy object
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String simpleMethodName = method.getName();
    Class[] params = method.getParameterTypes();

    // equals and hashCode are special cased
    if ("equals".equals(simpleMethodName) && params.length == 1 && params[0].equals(Object.class)) {
        Object value = args[0];
        if (value == null || !Proxy.isProxyClass(value.getClass())) {
            return Boolean.FALSE;
        }

        FastServletProxyInvocationHandler handler = (FastServletProxyInvocationHandler) Proxy
                .getInvocationHandler(value);

        return this.url.equals(handler.getURL()) ? Boolean.TRUE : Boolean.FALSE;
    }
    if ("hashCode".equals(simpleMethodName) && params.length == 0) {
        return Integer.valueOf(this.url.hashCode());
    }
    if ("toString".equals(simpleMethodName) && params.length == 0) {
        return "[FastServletProxyInvocationHandler " + this.url + ']';
    }

    return this.invokeRemoteMethod(proxy, method, args);
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void genericPoolShouldWorkWithPlainConnections() throws Exception {

    GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig(), false);

    borrowAndReturn(pool);//  ww  w. j a  v  a  2 s . c  o  m

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();
    pool.returnObject(connection);

    pool.close();
}

From source file:io.lettuce.core.support.AsyncConnectionPoolSupportTest.java

@Test
public void asyncPoolShouldWorkWithPlainConnections() {

    AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport
            .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri),
                    BoundedPoolConfig.create(), false);

    borrowAndReturn(pool);//from  w ww . ja  v  a  2 s .  c  o  m

    StatefulRedisConnection<String, String> connection = pool.acquire().join();
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();
    pool.release(connection);

    pool.close();
}

From source file:com.lambdaworks.redis.support.ConnectionPoolSupportTest.java

@Test
public void softReferencePoolShouldWorkWithPlainConnections() throws Exception {

    SoftReferenceObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport
            .createSoftReferenceObjectPool(() -> client.connect(), false);

    borrowAndReturn(pool);// www  .  jav  a 2  s .co m

    StatefulRedisConnection<String, String> connection = pool.borrowObject();
    assertThat(Proxy.isProxyClass(connection.getClass())).isFalse();
    pool.returnObject(connection);

    pool.close();
}