Search in sources :

Example 41 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project lombok by rzwitserloot.

the class AnnotationValues method getInstance.

/**
	 * Creates an actual annotation instance. You can use this to query any annotation methods, except for
	 * those annotation methods with class literals, as those can most likely not be turned into Class objects.
	 * 
	 * If some of the methods cannot be implemented, this method still works; it's only when you call a method
	 * that has a problematic value that an AnnotationValueDecodeFail exception occurs.
	 */
@SuppressWarnings("unchecked")
public A getInstance() {
    if (cachedInstance != null)
        return cachedInstance;
    InvocationHandler invocations = new InvocationHandler() {

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            AnnotationValue v = values.get(method.getName());
            if (v == null) {
                Object defaultValue = method.getDefaultValue();
                if (defaultValue != null)
                    return defaultValue;
                throw makeNoDefaultFail(v, method);
            }
            boolean isArray = false;
            Class<?> expected = method.getReturnType();
            Object array = null;
            if (expected.isArray()) {
                isArray = true;
                expected = expected.getComponentType();
                array = Array.newInstance(expected, v.valueGuesses.size());
            }
            if (!isArray && v.valueGuesses.size() > 1) {
                throw new AnnotationValueDecodeFail(v, "Expected a single value, but " + method.getName() + " has an array of values", -1);
            }
            if (v.valueGuesses.size() == 0 && !isArray) {
                Object defaultValue = method.getDefaultValue();
                if (defaultValue == null)
                    throw makeNoDefaultFail(v, method);
                return defaultValue;
            }
            int idx = 0;
            for (Object guess : v.valueGuesses) {
                Object result = guess == null ? null : guessToType(guess, expected, v, idx);
                if (!isArray) {
                    if (result == null) {
                        Object defaultValue = method.getDefaultValue();
                        if (defaultValue == null)
                            throw makeNoDefaultFail(v, method);
                        return defaultValue;
                    }
                    return result;
                }
                if (result == null) {
                    if (v.valueGuesses.size() == 1) {
                        Object defaultValue = method.getDefaultValue();
                        if (defaultValue == null)
                            throw makeNoDefaultFail(v, method);
                        return defaultValue;
                    }
                    throw new AnnotationValueDecodeFail(v, "I can't make sense of this annotation value. Try using a fully qualified literal.", idx);
                }
                Array.set(array, idx++, result);
            }
            return array;
        }
    };
    return cachedInstance = (A) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, invocations);
}
Also used : Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 42 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project carat by amplab.

the class PreferenceManagerCompat method setOnPreferenceTreeClickListener.

/**
     * Sets the callback to be invoked when a {@link Preference} in the
     * hierarchy rooted at this {@link PreferenceManager} is clicked.
     * 
     * @param listener The callback to be invoked.
     */
static void setOnPreferenceTreeClickListener(PreferenceManager manager, final OnPreferenceTreeClickListener listener) {
    try {
        Field onPreferenceTreeClickListener = PreferenceManager.class.getDeclaredField("mOnPreferenceTreeClickListener");
        onPreferenceTreeClickListener.setAccessible(true);
        if (listener != null) {
            Object proxy = Proxy.newProxyInstance(onPreferenceTreeClickListener.getType().getClassLoader(), new Class[] { onPreferenceTreeClickListener.getType() }, new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) {
                    if (method.getName().equals("onPreferenceTreeClick")) {
                        return Boolean.valueOf(listener.onPreferenceTreeClick((PreferenceScreen) args[0], (Preference) args[1]));
                    } else {
                        return null;
                    }
                }
            });
            onPreferenceTreeClickListener.set(manager, proxy);
        } else {
            onPreferenceTreeClickListener.set(manager, null);
        }
    } catch (Exception e) {
        Log.w(TAG, "Couldn't set PreferenceManager.mOnPreferenceTreeClickListener by reflection", e);
    }
}
Also used : Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 43 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project cassandra by apache.

the class JMXServerUtils method configureJmxAuthorization.

private static MBeanServerForwarder configureJmxAuthorization(Map<String, Object> env) {
    // If a custom authz proxy is supplied (Cassandra ships with AuthorizationProxy, which
    // delegates to its own role based IAuthorizer), then instantiate and return one which
    // can be set as the JMXConnectorServer's MBeanServerForwarder.
    // If no custom proxy is supplied, check system properties for the location of the
    // standard access file & stash it in env
    String authzProxyClass = System.getProperty("cassandra.jmx.authorizer");
    if (authzProxyClass != null) {
        final InvocationHandler handler = FBUtilities.construct(authzProxyClass, "JMX authz proxy");
        final Class[] interfaces = { MBeanServerForwarder.class };
        Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler);
        return MBeanServerForwarder.class.cast(proxy);
    } else {
        String accessFile = System.getProperty("com.sun.management.jmxremote.access.file");
        if (accessFile != null) {
            env.put("jmx.remote.x.access.file", accessFile);
        }
        return null;
    }
}
Also used : UnicastRemoteObject(java.rmi.server.UnicastRemoteObject) InvocationHandler(java.lang.reflect.InvocationHandler)

Example 44 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project retrofit by square.

the class BehaviorDelegate method returning.

// Single-interface proxy creation guarded by parameter safety.
@SuppressWarnings("unchecked")
public <R> T returning(Call<R> call) {
    final Call<R> behaviorCall = new BehaviorCall<>(behavior, executor, call);
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service }, new InvocationHandler() {

        @Override
        public T invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Type returnType = method.getGenericReturnType();
            Annotation[] methodAnnotations = method.getAnnotations();
            CallAdapter<R, T> callAdapter = (CallAdapter<R, T>) retrofit.callAdapter(returnType, methodAnnotations);
            return callAdapter.adapt(behaviorCall);
        }
    });
}
Also used : CallAdapter(retrofit2.CallAdapter) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type)

Example 45 with InvocationHandler

use of java.lang.reflect.InvocationHandler in project Shuttle by timusus.

the class PreferenceManagerCompat method setOnPreferenceTreeClickListener.

/**
     * Sets the callback to be invoked when a {@link Preference} in the
     * hierarchy rooted at this {@link PreferenceManager} is clicked.
     * 
     * @param listener The callback to be invoked.
     */
static void setOnPreferenceTreeClickListener(PreferenceManager manager, final OnPreferenceTreeClickListener listener) {
    try {
        Field onPreferenceTreeClickListener = PreferenceManager.class.getDeclaredField("mOnPreferenceTreeClickListener");
        onPreferenceTreeClickListener.setAccessible(true);
        if (listener != null) {
            Object proxy = Proxy.newProxyInstance(onPreferenceTreeClickListener.getType().getClassLoader(), new Class[] { onPreferenceTreeClickListener.getType() }, new InvocationHandler() {

                public Object invoke(Object proxy, Method method, Object[] args) {
                    if (method.getName().equals("onPreferenceTreeClick")) {
                        return Boolean.valueOf(listener.onPreferenceTreeClick((PreferenceScreen) args[0], (Preference) args[1]));
                    } else {
                        return null;
                    }
                }
            });
            onPreferenceTreeClickListener.set(manager, proxy);
        } else {
            onPreferenceTreeClickListener.set(manager, null);
        }
    } catch (Exception e) {
        Log.w(TAG, "Couldn't set PreferenceManager.mOnPreferenceTreeClickListener by reflection", e);
    }
}
Also used : Field(java.lang.reflect.Field) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler)

Aggregations

InvocationHandler (java.lang.reflect.InvocationHandler)179 Method (java.lang.reflect.Method)97 InvocationTargetException (java.lang.reflect.InvocationTargetException)24 Test (org.junit.Test)19 IOException (java.io.IOException)11 Proxy (java.lang.reflect.Proxy)10 Field (java.lang.reflect.Field)9 AccessibleObject (java.lang.reflect.AccessibleObject)7 ArrayList (java.util.ArrayList)6 NotNull (org.jetbrains.annotations.NotNull)6 Support_Proxy_I1 (tests.support.Support_Proxy_I1)6 Callable (java.util.concurrent.Callable)5 MBeanServerInvocationHandler (javax.management.MBeanServerInvocationHandler)5 LinkedHashMap (java.util.LinkedHashMap)4 Map (java.util.Map)4 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)3 RemoteObjectInvocationHandler (java.rmi.server.RemoteObjectInvocationHandler)3 Connection (java.sql.Connection)3 SQLException (java.sql.SQLException)3 HashMap (java.util.HashMap)3