Example usage for java.lang.reflect Method isAccessible

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

Introduction

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

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

/**
 * Set a value on a Bean, if its a persistent bean, try to use an update method first
 * (for v1.0 domain objects), otherwise use the setter (for v1.1 and above).
 *//*from w  ww  .  j  a  v a 2 s .  c o  m*/
static void updateProperty(PropertyDescriptor pd, Object value, Object source)
        throws IllegalAccessException, InvocationTargetException, TransformException {
    if (source instanceof Persistent) {
        if (pd != null && pd.getWriteMethod() != null) {
            try {
                Method m = source.getClass().getMethod("update" + StringHelper.getUpper1(pd.getName()),
                        pd.getWriteMethod().getParameterTypes());
                if (!m.isAccessible())
                    m.setAccessible(true);
                Class tClass = m.getParameterTypes()[0];
                if (value == null || tClass.isAssignableFrom(value.getClass())) {
                    m.invoke(source, new Object[] { value });
                    if (log.isDebugEnabled())
                        log.debug("Update property '" + pd.getName() + '=' + value + "' on object '"
                                + source.getClass().getName() + '\'');
                    // See if there is a datatype mapper for these classes
                } else if (DataTypeMapper.instance().isMappable(value.getClass(), tClass)) {
                    value = DataTypeMapper.instance().map(value, tClass);
                    m.invoke(source, new Object[] { value });
                    if (log.isDebugEnabled())
                        log.debug("Translate+Update property '" + pd.getName() + '=' + value + "' on object '"
                                + source.getClass().getName() + '\'');
                } else {
                    // Data type mismatch
                    throw new TransformException(TransformException.DATATYPE_MISMATCH,
                            source.getClass().getName() + '.' + m.getName(), tClass.getName(),
                            value.getClass().getName());
                }
            } catch (NoSuchMethodException e) {
                if (log.isDebugEnabled())
                    log.debug("No Updator, try Setter for DO property '" + pd.getName() + "' on object '"
                            + source.getClass().getName() + '\'');
                // try to use the setter if there is no update method
                setProperty(pd, value, source);
            }
        } else {
            TransformException me = new TransformException(TransformException.NO_SETTER, null,
                    pd == null ? "???" : pd.getName(), source.getClass().getName());
            log.error(me.getLocalizedMessage());
            throw me;
        }
    } else
        setProperty(pd, value, source);
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
    Method result = null;//www .java2s  . c o m
    final PropertyDescriptor propertyDescriptor = findPropertyDescriptorFor(clazz, propertyName);
    if (propertyDescriptor != null) {
        result = propertyDescriptor.getWriteMethod();
    }
    if (result == null) {
        Class<?> current = clazz;
        final String setterName = "set" + StringUtils.capitalize(propertyName);
        while (result == null && !Object.class.equals(current)) {
            final Method[] potentialMethods = current.getDeclaredMethods();
            for (Method potentialMethod : potentialMethods) {
                if (setterName.equals(potentialMethod.getName())) {
                    if (potentialMethod.getParameterTypes().length == 1) {
                        if (!mustBeStatic || Modifier.isStatic(potentialMethod.getModifiers())) {
                            if (!potentialMethod.isAccessible()) {
                                potentialMethod.setAccessible(true);
                            }
                            result = potentialMethod;
                        }
                    }
                }
            }
            current = current.getSuperclass();
        }
    }
    return result;
}

From source file:com.blackducksoftware.integration.hub.jenkins.site.BlackDuckHubUpdateSite.java

/**
 * This is where we store the update center data.
 * Mirrors {@link hudson.model.UpdateSite#getDataFile()}
 */// w  w  w .jav  a2s .  c  om
private TextFile getDataFile() {
    try {
        // try reflection to be safe for the parent class changing the location
        final Method method = UpdateSite.class.getDeclaredMethod("getDataFile");
        final boolean accessible = method.isAccessible();
        try {
            method.setAccessible(true);
            return (TextFile) method.invoke(this);
        } finally {
            if (!accessible) {
                method.setAccessible(false);
            }
        }
    } catch (final Throwable e) {
        // ignore
    }
    return new TextFile(new File(Jenkins.getInstance().getRootDir(), "updates/" + getId() + ".json"));
}

From source file:de.matzefratze123.heavyspleef.commands.base.CommandManagerService.java

protected void executeCommand(CommandContext context) {
    Method method = context.getCommand().getCommandMethod();
    Object instance = context.getCommand().getCommandClassInstance();

    boolean accessible = method.isAccessible();
    method.setAccessible(true);//www. j ava2s .c  o  m

    //Analyse the method
    //Default method format is: methodName(CommandContext)

    try {
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            //No parameters in this method, so just invoke it
            method.invoke(instance);
        } else {
            Object[] parameterValues = new Object[parameterTypes.length];

            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> parameterType = parameterTypes[i];

                if (parameterType == CommandContext.class) {
                    parameterValues[i] = context;
                } else if (plugin.getClass() == parameterType) {
                    parameterValues[i] = plugin;
                } else if (parameterType.isPrimitive()) {
                    parameterValues[i] = getDefaultPrimitiveValue(parameterType);
                } else {
                    for (Object arg : args) {
                        if (parameterType.isInstance(arg)) {
                            parameterValues[i] = arg;
                            break;
                        }
                    }
                }
            }

            method.invoke(instance, parameterValues);
        }
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();

        if (cause instanceof CommandException) {
            ((CommandException) cause).sendToPlayer(context.getSender());
        } else {
            logger.log(Level.SEVERE,
                    "Unhandled exception executing command \"" + context.getCommand().getName() + "\"", cause);
        }
    } catch (IllegalAccessException | IllegalArgumentException e) {
        logger.log(Level.SEVERE,
                "Could not invoke command method for '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } catch (Exception e) {
        logger.log(Level.SEVERE,
                "Unhandled exception executing command '" + context.getCommand().getFullyQualifiedName() + "'",
                e);
    } finally {
        method.setAccessible(accessible);
    }
}

From source file:com.cloudbees.jenkins.plugins.enterpriseplugins.CloudBeesUpdateSite.java

/**
 * This is where we store the update center data.
 * Mirrors {@link hudson.model.UpdateSite#getDataFile()}
 *///w w  w .  j a v a 2 s . c om
private TextFile getDataFile() {
    try {
        // try reflection to be safe for the parent class changing the location
        Method method = UpdateSite.class.getDeclaredMethod("getDataFile");
        boolean accessible = method.isAccessible();
        try {
            method.setAccessible(true);
            return (TextFile) method.invoke(this);
        } finally {
            if (!accessible) {
                method.setAccessible(false);
            }
        }
    } catch (Throwable e) {
        // ignore
    }
    return new TextFile(new File(Hudson.getInstance().getRootDir(), "updates/" + getId() + ".json"));
}

From source file:org.apache.nifi.registry.security.authentication.IdentityProviderFactory.java

private void performMethodInjection(final IdentityProvider instance, final Class loginIdentityProviderClass)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    for (final Method method : loginIdentityProviderClass.getMethods()) {
        if (method.isAnnotationPresent(IdentityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);//from ww w. j av a2  s  .  c o m

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = loginIdentityProviderClass.getSuperclass();
    if (parentClass != null && IdentityProvider.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}

From source file:com.autentia.wuija.persistence.event.AnnotationEventListener.java

private Object invokeAnnotatedMethod(Session session, Object entity, Class<? extends Annotation> annotation) {
    final Method annotatedMethod = ClassUtils.findAnnotatedMethod(entity.getClass(), annotation);
    if (annotatedMethod == null) {
        return null;
    }/*from w  w w. ja va  2s.  c o m*/

    if (log.isDebugEnabled()) {
        log.debug(
                "Invoking " + annotation.getSimpleName() + " method, for class " + entity.getClass().getName());
    }

    final boolean accesible = annotatedMethod.isAccessible();
    annotatedMethod.setAccessible(true); // Se hace el mtodo accesible, por si es privado
    try {
        if (annotatedMethod.getParameterTypes().length == 1) {
            return annotatedMethod.invoke(entity, session);
        }
        return annotatedMethod.invoke(entity);

    } catch (IllegalArgumentException e) {
        final String msg = "Cannot invoke event listener method. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " should have no parameters, or just one parameter, the Hibernate session.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } catch (IllegalAccessException e) {
        final String msg = "Cannot invoke event listener. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " is not accesible.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } catch (InvocationTargetException e) {
        final String msg = "Cannot invoke event listener. Method for class "
                + annotatedMethod.getDeclaringClass().getName() + "." + annotatedMethod.getName()
                + " is not accesible.";
        log.fatal(msg, e);
        throw new IllegalArgumentException(msg, e);

    } finally {
        annotatedMethod.setAccessible(accesible); // Se restaura la accesibilidad del metodo
    }
}

From source file:com.jaredrummler.materialspinner.MaterialSpinner.java

@Override
public void setBackgroundColor(int color) {
    backgroundColor = color;/*from w w  w. ja v a2s.co m*/
    Drawable background = getBackground();
    if (background instanceof StateListDrawable) { // pre-L
        try {
            Method getStateDrawable = StateListDrawable.class.getDeclaredMethod("getStateDrawable", int.class);
            if (!getStateDrawable.isAccessible())
                getStateDrawable.setAccessible(true);
            int[] colors = { darker(color, 0.85f), color };
            for (int i = 0; i < colors.length; i++) {
                ColorDrawable drawable = (ColorDrawable) getStateDrawable.invoke(background, i);
                drawable.setColor(colors[i]);
            }
        } catch (Exception e) {
            Log.e("MaterialSpinner", "Error setting background color", e);
        }
    } else if (background != null) { // 21+ (RippleDrawable)
        background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
    }
    popupWindow.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}

From source file:org.vulpe.commons.util.VulpeReflectUtil.java

/**
 * Sets field value in object.//from w ww. j  av  a2 s.  co m
 *
 * @param object
 * @param fieldName
 * @param value
 */
public static void setFieldValue(final Object object, final String fieldName, final Object value) {
    try {
        final String name = VulpeStringUtil.upperCaseFirst(fieldName);
        Method method = null;
        Class<?> classField = (value == null ? getFieldClass(object.getClass(), fieldName) : value.getClass());
        while (classField != null && !classField.equals(Object.class)) {
            method = getMethod(object.getClass(), "set".concat(name), classField);
            if (method != null) {
                break;
            }
            classField = classField.getSuperclass();
        }
        if (method != null) {
            synchronized (method) {
                boolean setted = false;
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                    setted = true;
                }
                try {
                    method.invoke(object, value);
                } catch (Exception e) {
                    LOG.error(e.getMessage());
                } finally {
                    if (setted) {
                        method.setAccessible(false);
                    }
                }
            }
        } else {
            final Field field = getField(object.getClass(), fieldName);
            if (field != null) {
                synchronized (field) {
                    boolean setted = false;
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                        setted = true;
                    }
                    try {
                        if (field.getType().isAssignableFrom(value.getClass())) {
                            field.set(object, value);
                        } else {
                            Object newValue = value;
                            if (Long.class.isAssignableFrom(field.getType())) {
                                newValue = new Long(value.toString());
                            }
                            field.set(object, newValue);
                        }
                    } finally {
                        if (setted) {
                            field.setAccessible(false);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new VulpeSystemException(e);
    }
}

From source file:org.beangle.security.web.context.HttpSessionContextIntegrationFilter.java

/**
 * Gets the security context from the session (if available) and returns it.
 * <p/>/*from w  ww .  j  av  a  2 s.  c o  m*/
 * If the session is null, the context object is null or the context object stored in the
 * session is not an instance of SecurityContext it will return null.
 * <p/>
 * If <tt>cloneFromHttpSession</tt> is set to true, it will attempt to clone the context object
 * and return the cloned instance.
 * 
 * @param httpSession
 *            the session obtained from the request.
 */
private SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        logger.debug("No HttpSession currently exists");
        return null;
    }

    // Session exists, so try to obtain a context from it.
    Object contextFromSessionObject = httpSession.getAttribute(SECURITY_CONTEXT_KEY);
    if (contextFromSessionObject == null) {
        logger.debug("HttpSession returned null object for BEANGLE_SECURITY_CONTEXT");
        return null;
    }

    // We now have the security context object from the session.

    // Clone if required (see SEC-356)
    if (cloneFromHttpSession) {
        Validate.isTrue(contextFromSessionObject instanceof Cloneable,
                "Context must implement Clonable and provide a Object.clone() method");
        try {
            Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {});
            if (!m.isAccessible()) {
                m.setAccessible(true);
            }
            contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {});
        } catch (Exception ex) {
            ReflectionUtils.handleReflectionException(ex);
        }
    }

    if (!(contextFromSessionObject instanceof SecurityContext)) {
        if (logger.isWarnEnabled()) {
            logger.warn("BEANGLE_SECURITY_CONTEXT did not contain a SecurityContext but contained: '"
                    + contextFromSessionObject + "'; are you improperly modifying the HttpSession directly "
                    + "(you should always use SecurityContextHolder) or using the HttpSession attribute "
                    + "reserved for this class?");
        }

        return null;
    }

    // Everything OK. The only non-null return from this method.

    return (SecurityContext) contextFromSessionObject;
}