Example usage for java.lang.reflect Method setAccessible

List of usage examples for java.lang.reflect Method setAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Method setAccessible.

Prototype

@Override
@CallerSensitive
public void setAccessible(boolean flag) 

Source Link

Usage

From source file:com.abstratt.mdd.core.util.MDDUtil.java

private static IActivityNodeTreeVisitor.Outcome visitNode(ActivityNode node, IActivityNodeTreeVisitor visitor) {
    String eClassName = node.eClass().getName();
    try {//  w  w w .  java2 s. c  o  m
        Method visitorMethod;
        try {
            visitorMethod = visitor.getClass().getDeclaredMethod("visit" + eClassName,
                    node.eClass().getInstanceClass());
        } catch (NoSuchMethodException e) {
            // fallback: call visitAny(ActitivityNode) instead
            visitorMethod = visitor.getClass().getDeclaredMethod("visitAny", ActivityNode.class);
        }
        visitorMethod.setAccessible(true);
        return (Outcome) visitorMethod.invoke(visitor, node);
    } catch (NoSuchMethodException e) {
        // keep going...
    } catch (IllegalAccessException e) {
        LogUtils.logWarning(MDDCore.PLUGIN_ID, "Unexpected error", e);
    } catch (InvocationTargetException e) {
        LogUtils.logWarning(MDDCore.PLUGIN_ID, "Unexpected error", e);
    }
    // no visitor method found, continue
    return IActivityNodeTreeVisitor.Outcome.CONTINUE;
}

From source file:com.ett.common.util.ReflectUtil.java

/**
 * @param object// w  w w. ja  v a 2 s .  c  om
 * @param methodName
 * @param params
 * @return
 * @throws NoSuchMethodException
 */
public static Object invokePrivateMethod(Object object, String methodName, Object... params)
        throws NoSuchMethodException {
    Assert.notNull(object);
    Assert.hasText(methodName);
    Class[] types = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
        types[i] = params[i].getClass();
    }

    Class clazz = object.getClass();
    Method method = null;
    for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
        try {
            method = superClass.getDeclaredMethod(methodName, types);
            break;
        } catch (NoSuchMethodException e) {
            // ??17,?
        }
    }

    if (method == null)
        throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

    boolean accessible = method.isAccessible();
    method.setAccessible(true);
    Object result = null;
    try {
        result = method.invoke(object, params);
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
    }
    method.setAccessible(accessible);
    return result;
}

From source file:com.austin.base.commons.util.ReflectUtil.java

/**
 * @param object//from   www .  j av  a 2 s  . com
 * @param methodName
 * @param params
 * @return
 * @throws NoSuchMethodException
 */
public static Object invokePrivateMethod(Object object, String methodName, Object... params)
        throws NoSuchMethodException {
    Assert.notNull(object);
    Assert.hasText(methodName);
    Class[] types = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
        types[i] = params[i].getClass();
    }

    Class clazz = object.getClass();
    Method method = null;
    for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
        try {
            method = superClass.getDeclaredMethod(methodName, types);
            break;
        } catch (NoSuchMethodException e) {
            // ??17,?
        }
    }

    if (method == null)
        throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

    boolean accessible = method.isAccessible();
    method.setAccessible(true);
    Object result = null;
    try {
        result = method.invoke(object, params);
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
    }
    method.setAccessible(accessible);
    return result;
}

From source file:info.guardianproject.netcipher.web.WebkitProxy.java

private static boolean setWebkitProxyICS(Context ctx, String host, int port) {

    // PSIPHON: added support for Android 4.x WebView proxy
    try {/*ww  w.j  a  v a 2  s . co  m*/
        Class webViewCoreClass = Class.forName("android.webkit.WebViewCore");

        Class proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
        if (webViewCoreClass != null && proxyPropertiesClass != null) {
            Method m = webViewCoreClass.getDeclaredMethod("sendStaticMessage", Integer.TYPE, Object.class);
            Constructor c = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE, String.class);

            if (m != null && c != null) {
                m.setAccessible(true);
                c.setAccessible(true);
                Object properties = c.newInstance(host, port, null);

                // android.webkit.WebViewCore.EventHub.PROXY_CHANGED = 193;
                m.invoke(null, 193, properties);

                return true;
            }

        }
    } catch (Exception e) {
        Log.e("ProxySettings",
                "Exception setting WebKit proxy through android.net.ProxyProperties: " + e.toString());
    } catch (Error e) {
        Log.e("ProxySettings",
                "Exception setting WebKit proxy through android.webkit.Network: " + e.toString());
    }

    return false;

}

From source file:com.ms.commons.test.common.ReflectUtil.java

public static Object invokeMethodByMemoryRow(Object object, Method method, MemoryRow memoryRow,
        Mutable outParameters) {//from  ww  w .j a  v  a  2s  .c o m
    Class<?>[] parameterTypes = method.getParameterTypes();
    method.getTypeParameters();
    Object[] parameterObjects = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> clazz = parameterTypes[i];
        MemoryField field = memoryRow.getField(i + 1);
        Object value = (field.getType() == MemoryFieldType.Null) ? null : field.getValue();
        parameterObjects[i] = TypeConvertUtil.convert(clazz, value);
    }
    if (outParameters != null) {
        outParameters.setValue(Arrays.asList(parameterObjects));
    }
    try {
        method.setAccessible(true);
        return method.invoke(object, parameterObjects);
    } catch (Exception e) {
        throw ExceptionUtil.wrapToRuntimeException(e);
    }
}

From source file:ca.oson.json.util.ObjectUtil.java

@SuppressWarnings("unchecked")
public static <E> void setMethodValue(E obj, Method method, Object... args) {
    try {//from   www .j a v  a2s. c  o m
        method.setAccessible(true);

        method.invoke(obj, args);

    } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
        // e.printStackTrace();
        try {
            if (obj != null) {
                Statement stmt = new Statement(obj, method.getName(), args);
                stmt.execute();
            }

        } catch (Exception e1) {
            // e1.printStackTrace();
        }
    }
}

From source file:JarClassLoader.java

public void invokeClass(String name, String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
    Class c = loadClass(name);//from  w  w w.  j av a2s.  c  o  m
    Method m = c.getMethod("main", new Class[] { args.getClass() });
    m.setAccessible(true);
    int mods = m.getModifiers();
    if (m.getReturnType() != void.class || !Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
        throw new NoSuchMethodException("main");
    }
    try {
        m.invoke(null, new Object[] { args });
    } catch (IllegalAccessException e) {

    }
}

From source file:ca.oson.json.util.ObjectUtil.java

@SuppressWarnings("unchecked")
public static <E, R> R getMethodValue(E obj, Method method, Object... args) {
    R value = null;//from ww w .j  a  v  a  2s . c  o  m

    try {
        method.setAccessible(true);

        value = (R) method.invoke(obj, args);
    } catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
        // e.printStackTrace();
        try {
            if (obj != null) {
                Expression expr = new Expression(obj, method.getName(), args);
                expr.execute();
                value = (R) expr.getValue();
            }

            if (value == null) {
                value = (R) method.getDefaultValue();
            }

        } catch (Exception e1) {
            // e1.printStackTrace();
        }
    }

    return value;
}

From source file:com.icesoft.faces.context.BridgeFacesContext.java

/**
 * Check the delegation chain for a BridgeFacesContext wrapped by another
 *
 * @param facesContext return BridgeFacesContext (if found) or input FacesContext
 *///  ww  w. ja va 2s  .  com
public static FacesContext unwrap(FacesContext facesContext) {
    if (facesContext instanceof BridgeFacesContext) {
        return facesContext;
    }
    FacesContext result = facesContext;
    try {
        Method delegateMethod = facesContext.getClass().getDeclaredMethod("getDelegate", new Class[] {});
        delegateMethod.setAccessible(true);
        Object delegate = delegateMethod.invoke(facesContext, (Object[]) null);
        if (delegate instanceof BridgeFacesContext) {
            result = (FacesContext) delegate;
            // #3668 fetch messages from Spring
            Iterator clientIdIterator = facesContext.getClientIdsWithMessages();
            FacesMessage message;
            String clientId;
            while (clientIdIterator.hasNext()) {
                clientId = (String) clientIdIterator.next();
                Iterator facesMessagesForClientId = facesContext.getMessages(clientId);
                while (facesMessagesForClientId.hasNext()) {
                    message = (FacesMessage) facesMessagesForClientId.next();
                    result.addMessage(clientId, message);
                }
            }
            Iterator facesMessagesWithNoId = facesContext.getMessages(null);
            while (facesMessagesWithNoId.hasNext()) {
                message = (FacesMessage) facesMessagesWithNoId.next();
                result.addMessage("", message);
            }
            if (log.isDebugEnabled()) {
                log.debug("BridgeFacesContext delegate of " + facesContext);
            }
        }
    } catch (Exception e) {
    }

    return result;
}

From source file:fi.foyt.foursquare.api.JSONFieldParser.java

/**
 * Static method that parses single JSON Object into FoursquareEntity
 * /*from ww  w.ja  v  a2s. c  o m*/
 * @param clazz entity class
 * @param jsonObject JSON Object
 * @param skipNonExistingFields whether parser should ignore non-existing fields
 * @return entity
 * @throws FoursquareApiException when something unexpected happens
 */
public static FoursquareEntity parseEntity(Class<?> clazz, JSONObject jsonObject, boolean skipNonExistingFields)
        throws FoursquareApiException {
    FoursquareEntity entity = createNewEntity(clazz);

    String[] objectFieldNames = getFieldNames(jsonObject);
    if (objectFieldNames != null) {
        for (String objectFieldName : objectFieldNames) {
            Class<?> fieldClass = getFieldClass(entity.getClass(), objectFieldName);
            if (fieldClass == null) {
                Method setterMethod = getSetterMethod(entity.getClass(), objectFieldName);
                if (setterMethod == null) {
                    if (!skipNonExistingFields) {
                        throw new FoursquareApiException("Could not find field " + objectFieldName + " from "
                                + entity.getClass().getName() + " class");
                    }
                } else {
                    Class<?>[] parameters = setterMethod.getParameterTypes();
                    if (parameters.length == 1) {
                        fieldClass = parameters[0];

                        try {
                            setterMethod.setAccessible(true);
                            setterMethod.invoke(entity,
                                    parseValue(fieldClass, jsonObject, objectFieldName, skipNonExistingFields));
                        } catch (JSONException e) {
                            throw new FoursquareApiException(e);
                        } catch (IllegalArgumentException e) {
                            throw new FoursquareApiException(e);
                        } catch (IllegalAccessException e) {
                            throw new FoursquareApiException(e);
                        } catch (InvocationTargetException e) {
                            throw new FoursquareApiException(e);
                        }
                    } else {
                        throw new FoursquareApiException("Could not find field " + objectFieldName + " from "
                                + entity.getClass().getName() + " class");
                    }
                }
            } else {
                try {
                    setEntityFieldValue(entity, objectFieldName,
                            parseValue(fieldClass, jsonObject, objectFieldName, skipNonExistingFields));
                } catch (JSONException e) {
                    throw new FoursquareApiException(e);
                }
            }
        }
    }

    return entity;
}