Search in sources :

Example 1 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project elasticsearch by elastic.

the class FactoryProvider method get.

@Override
public F get() {
    InvocationHandler invocationHandler = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] creationArgs) throws Throwable {
            // pass methods from Object.class to the proxy
            if (method.getDeclaringClass().equals(Object.class)) {
                return method.invoke(this, creationArgs);
            }
            AssistedConstructor<?> constructor = factoryMethodToConstructor.get(method);
            Object[] constructorArgs = gatherArgsForConstructor(constructor, creationArgs);
            Object objectToReturn = constructor.newInstance(constructorArgs);
            injector.injectMembers(objectToReturn);
            return objectToReturn;
        }

        public Object[] gatherArgsForConstructor(AssistedConstructor<?> constructor, Object[] factoryArgs) {
            int numParams = constructor.getAllParameters().size();
            int argPosition = 0;
            Object[] result = new Object[numParams];
            for (int i = 0; i < numParams; i++) {
                Parameter parameter = constructor.getAllParameters().get(i);
                if (parameter.isProvidedByFactory()) {
                    result[i] = factoryArgs[argPosition];
                    argPosition++;
                } else {
                    result[i] = parameter.getValue(injector);
                }
            }
            return result;
        }
    };
    // we imprecisely treat the class literal of T as a Class<T>
    @SuppressWarnings("unchecked") Class<F> factoryRawType = (Class) factoryType.getRawType();
    return factoryRawType.cast(Proxy.newProxyInstance(factoryRawType.getClassLoader(), new Class[] { factoryRawType }, invocationHandler));
}
Also used : Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 2 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project buck by facebook.

the class Connection method setRemoteInterface.

@SuppressWarnings("unchecked")
public void setRemoteInterface(Class<REMOTE> remoteInterface, ClassLoader classLoader) {
    checkNotClose();
    InvocationHandler invocationHandler = (proxy, method, args) -> {
        InvocationMessage invocation = new InvocationMessage(method.getName(), Arrays.asList(args));
        ReturnResultMessage response = messageTransport.sendMessageAndWaitForResponse(invocation);
        return response.getValue();
    };
    this.remoteObjectProxy = (REMOTE) Proxy.newProxyInstance(classLoader, new Class[] { remoteInterface }, invocationHandler);
}
Also used : Arrays(java.util.Arrays) Proxy(java.lang.reflect.Proxy) Preconditions(com.google.common.base.Preconditions) InvocationHandler(java.lang.reflect.InvocationHandler) Nullable(javax.annotation.Nullable) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 3 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project javaslang by javaslang.

the class Lazy method val.

/**
     * Creates a real _lazy value_ of type {@code T}, backed by a {@linkplain java.lang.reflect.Proxy} which delegates
     * to a {@code Lazy} instance.
     *
     * @param supplier A supplier
     * @param type     An interface
     * @param <T>      type of the lazy value
     * @return A new instance of T
     */
@GwtIncompatible("reflection is not supported")
@SuppressWarnings("unchecked")
public static <T> T val(Supplier<? extends T> supplier, Class<T> type) {
    Objects.requireNonNull(supplier, "supplier is null");
    Objects.requireNonNull(type, "type is null");
    if (!type.isInterface()) {
        throw new IllegalArgumentException("type has to be an interface");
    }
    final Lazy<T> lazy = Lazy.of(supplier);
    final InvocationHandler handler = (proxy, method, args) -> method.invoke(lazy.get(), args);
    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, handler);
}
Also used : Option(javaslang.control.Option) Proxy(java.lang.reflect.Proxy) Predicate(java.util.function.Predicate) Seq(javaslang.collection.Seq) IOException(java.io.IOException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Serializable(java.io.Serializable) Objects(java.util.Objects) Consumer(java.util.function.Consumer) Iterator(javaslang.collection.Iterator) ObjectOutputStream(java.io.ObjectOutputStream) InvocationHandler(java.lang.reflect.InvocationHandler) NoSuchElementException(java.util.NoSuchElementException) Vector(javaslang.collection.Vector) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 4 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project ormlite-android by j256.

the class DatabaseTableConfigUtil method buildConfig.

/**
	 * Instead of calling the annotation methods directly, we peer inside the proxy and investigate the array of
	 * AnnotationMember objects stored by the AnnotationFactory.
	 */
private static DatabaseFieldConfig buildConfig(DatabaseField databaseField, String tableName, Field field) throws Exception {
    InvocationHandler proxy = Proxy.getInvocationHandler(databaseField);
    if (proxy.getClass() != annotationFactoryClazz) {
        return null;
    }
    // this should be an array of AnnotationMember objects
    Object elementsObject = elementsField.get(proxy);
    if (elementsObject == null) {
        return null;
    }
    DatabaseFieldConfig config = new DatabaseFieldConfig(field.getName());
    Object[] objs = (Object[]) elementsObject;
    for (int i = 0; i < configFieldNums.length; i++) {
        Object value = valueField.get(objs[i]);
        if (value != null) {
            assignConfigField(configFieldNums[i], config, field, value);
        }
    }
    return config;
}
Also used : DatabaseFieldConfig(com.j256.ormlite.field.DatabaseFieldConfig) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 5 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project jna by java-native-access.

the class Native method synchronizedLibrary.

/**
     * Returns a synchronized (thread-safe) library backed by the specified
     * library.  This wrapping will prevent simultaneous invocations of any
     * functions mapped to a given {@link NativeLibrary}.  Note that the
     * native library may still be sensitive to being called from different
     * threads.
     * <p>
     * @param  library the library to be "wrapped" in a synchronized library.
     * @return a synchronized view of the specified library.
     */
public static Library synchronizedLibrary(final Library library) {
    Class<?> cls = library.getClass();
    if (!Proxy.isProxyClass(cls)) {
        throw new IllegalArgumentException("Library must be a proxy class");
    }
    InvocationHandler ih = Proxy.getInvocationHandler(library);
    if (!(ih instanceof Library.Handler)) {
        throw new IllegalArgumentException("Unrecognized proxy handler: " + ih);
    }
    final Library.Handler handler = (Library.Handler) ih;
    InvocationHandler newHandler = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            synchronized (handler.getNativeLibrary()) {
                return handler.invoke(library, method, args);
            }
        }
    };
    return (Library) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), newHandler);
}
Also used : UncaughtExceptionHandler(com.sun.jna.Callback.UncaughtExceptionHandler) InvocationHandler(java.lang.reflect.InvocationHandler) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Aggregations

InvocationHandler (java.lang.reflect.InvocationHandler)406 Method (java.lang.reflect.Method)228 Test (org.junit.Test)70 InvocationTargetException (java.lang.reflect.InvocationTargetException)53 Proxy (java.lang.reflect.Proxy)27 ArrayList (java.util.ArrayList)25 Map (java.util.Map)22 IOException (java.io.IOException)19 Field (java.lang.reflect.Field)19 HashMap (java.util.HashMap)18 List (java.util.List)16 AccessibleObject (java.lang.reflect.AccessibleObject)15 BindingProvider (javax.xml.ws.BindingProvider)14 PersistentClass (org.hibernate.mapping.PersistentClass)12 RootClass (org.hibernate.mapping.RootClass)12 Before (org.junit.Before)10 Connection (java.sql.Connection)9 LinkedHashMap (java.util.LinkedHashMap)8 AbstractQueryFacade (org.jboss.tools.hibernate.runtime.common.AbstractQueryFacade)8 DexMakerTest (com.android.dx.DexMakerTest)7