Example usage for org.springframework.util ReflectionUtils makeAccessible

List of usage examples for org.springframework.util ReflectionUtils makeAccessible

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils makeAccessible.

Prototype

@SuppressWarnings("deprecation") 
public static void makeAccessible(Field field) 

Source Link

Document

Make the given field accessible, explicitly setting it accessible if necessary.

Usage

From source file:org.alfresco.util.test.junitrules.TemporaryMockOverride.java

@Override
protected void after() {
    // For all objects that have been tampered with, we'll revert them to their original state.
    for (int i = pristineFieldValues.size() - 1; i >= 0; i--) {
        FieldValueOverride override = pristineFieldValues.get(i);

        if (log.isDebugEnabled()) {
            log.debug("Reverting mocked field '" + override.fieldName + "' on object "
                    + override.objectContainingField + " to original value '" + override.fieldPristineValue
                    + "'");
        }//  w w  w.jav a 2 s. c o m

        // Hack into the Java field object
        Field f = ReflectionUtils.findField(override.objectContainingField.getClass(), override.fieldName);
        ReflectionUtils.makeAccessible(f);
        // and revert its value.
        ReflectionUtils.setField(f, override.objectContainingField, override.fieldPristineValue);
    }
}

From source file:org.alfresco.util.test.junitrules.TemporaryMockOverride.java

public void setTemporaryField(Object objectContainingField, String fieldName, Object fieldValue) {
    if (log.isDebugEnabled()) {
        log.debug("Overriding field '" + fieldName + "' on object " + objectContainingField + " to new value '"
                + fieldValue + "'");
    }//w  w w  .j a  v  a2 s .  c  om

    // Extract the pristine value of the field we're going to mock.
    Field f = ReflectionUtils.findField(objectContainingField.getClass(), fieldName);

    if (f == null) {
        final String msg = "Object of type '" + objectContainingField.getClass().getSimpleName()
                + "' has no field named '" + fieldName + "'";
        if (log.isDebugEnabled()) {
            log.debug(msg);
        }
        throw new IllegalArgumentException(msg);
    }

    ReflectionUtils.makeAccessible(f);
    Object pristineValue = ReflectionUtils.getField(f, objectContainingField);

    // and add it to the list.
    pristineFieldValues.add(new FieldValueOverride(objectContainingField, fieldName, pristineValue));

    // and set it on the object
    ReflectionUtils.setField(f, objectContainingField, fieldValue);
}

From source file:org.apache.camel.spring.postprocessor.MagicAnnotationPostProcessor.java

@Override
public boolean postProcessAfterInstantiation(final Object bean, final String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            MagicAnnotation annotation = field.getAnnotation(MagicAnnotation.class);
            if (annotation != null && field.getType() == String.class) {
                log.info("Found MagicAnnotation on field " + field + " of class " + bean.getClass());

                ReflectionUtils.makeAccessible(field);
                field.set(bean, annotation.value());
            }//from  w w w . j  a  v  a 2 s. com
        }
    });

    return true;
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

private <T> T getFieldValue(Object object, String fieldName, Class<T> fieldType) {

    Field field = ReflectionUtils.findField(object.getClass(), fieldName, fieldType);

    ReflectionUtils.makeAccessible(field);

    return (T) ReflectionUtils.getField(field, object);

}

From source file:org.codehaus.groovy.grails.commons.AbstractGrailsClass.java

public boolean isActionMethod(String methodName) {
    Method m = ReflectionUtils.findMethod(getClazz(), methodName, new Class[0]);
    if (m != null) {
        ReflectionUtils.makeAccessible(m);
    }/* w  w w.j a  va 2  s.  co  m*/
    return m != null && m.getAnnotation(Action.class) != null;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventListener.java

private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
    Method method = ReflectionUtils.findMethod(domainClazz, event);
    if (method != null) {
        ReflectionUtils.makeAccessible(method);
        return new MethodCaller(method);
    }// w  ww  .ja  v a  2  s. c o  m

    Field field = ReflectionUtils.findField(domainClazz, event);
    if (field != null) {
        ReflectionUtils.makeAccessible(field);
        return new FieldClosureCaller(field);
    }

    MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
    if (metaMethod != null) {
        return new MetaMethodCaller(metaMethod);
    }

    MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
    if (metaProperty != null) {
        return new MetaPropertyClosureCaller(metaProperty);
    }

    return null;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.java

public ClosureEventTriggeringInterceptor() {
    try {/*from  w  w w.  j  a va  2 s .  co m*/
        markInterceptorDirtyMethod = ReflectionUtils.findMethod(AbstractSaveEventListener.class,
                "markInterceptorDirty", new Class[] { Object.class, EntityPersister.class, EventSource.class });
        ReflectionUtils.makeAccessible(markInterceptorDirtyMethod);
    } catch (Exception e) {
        // ignore
    }
}

From source file:org.dspace.app.rest.utils.RestRepositoryUtils.java

public Object invokeQueryMethod(DSpaceRestRepository repository, Method method,
        MultiValueMap<String, ? extends Object> parameters, Pageable pageable, Sort sort) {

    Assert.notNull(method, "Method must not be null!");
    Assert.notNull(parameters, "Parameters must not be null!");

    ReflectionUtils.makeAccessible(method);

    return ReflectionUtils.invokeMethod(method, repository,
            prepareParameters(method, parameters, pageable, sort));
}

From source file:org.finra.herd.service.activiti.HerdCommandInvoker.java

/**
 * Gets the JobEntity from the given ExecuteAsyncJobCmd.
 *
 * @param executeAsyncJobCmd The ExecuteAsyncJobCmd
 *
 * @return The JobEntity/*from w ww .  j  a v a  2 s.c o m*/
 */
private JobEntity getJobEntity(ExecuteAsyncJobCmd executeAsyncJobCmd) {
    /*
     * Unfortunately, ExecuteAsyncJobCmd does not provide an accessible method to get the JobEntity stored within it.
     * We use reflection to force the value out of the object.
     * Also, we cannot simply get the entity and update it. We must retrieve it through the entity manager so it registers in Activiti's persistent object
     * cache. This way when the transaction commits, Activiti is aware of any changes in the JobEntity and persists them correctly.
     */
    try {
        Field field = ExecuteAsyncJobCmd.class.getDeclaredField("job");
        ReflectionUtils.makeAccessible(field);
        String jobId = ((JobEntity) ReflectionUtils.getField(field, executeAsyncJobCmd)).getId();

        return Context.getCommandContext().getJobEntityManager().findJobById(jobId);
    } catch (NoSuchFieldException | SecurityException e) {
        /*
         * This exception should not happen.
         */
        throw new IllegalStateException(e);
    }
}

From source file:org.kuali.student.common.spring.WebServiceAwareSpringBeanPostProcessor.java

@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {

    Class<? extends Object> beanClass = bean.getClass();

    try {// ww w. j ava  2s.c  o  m
        super.processInjection(bean);

    } catch (BeansException e2) {
        // any resolved beans from the local applicationContext will have been injected into the bean by now
        // so fall through.
        // we will only update the @Autowired fields that are null and declare @WebService annotations.
    }

    Field[] fields = beanClass.getDeclaredFields();

    for (Field field : fields) {

        // check for the @Autowired, @Resource, or @Value annotation
        if (!fieldHasInjectionAnnotation(field))
            continue; // skip fields that don't have an injection annotation

        Object currentValue = null;
        try {

            ReflectionUtils.makeAccessible(field);

            currentValue = field.get(bean);

        } catch (IllegalArgumentException e1) {
            log.warn("get error", e1);
            continue;

        } catch (SecurityException e1) {
            log.warn("get error", e1);
            continue;
        } catch (IllegalAccessException e1) {
            log.warn("get error", e1);
            continue;
        }

        // Only resolve using KSB if the object value has not been set.
        if (currentValue != null)
            continue; // was handled already

        Class<?> fieldType = field.getType();

        WebService webServiceAnnotation = (WebService) fieldType.getAnnotation(WebService.class);

        if (webServiceAnnotation != null) {

            // we can only auto resolve if the @WebService annotation is
            // present.

            String namespace = webServiceAnnotation.targetNamespace();
            String serviceName = webServiceAnnotation.serviceName();

            if (serviceName.isEmpty())
                serviceName = webServiceAnnotation.name();

            if (namespace != null) {

                // First check to see if the application context has a reference 
                // using the serivceName

                try {

                    Object service = null;
                    try {
                        service = beanFactory.getBean(serviceName, fieldType);
                    } catch (NoSuchBeanDefinitionException e) {
                        service = null;
                        // fall through
                    }

                    if (service != null) {
                        injectServiceReference(bean, beanName, field, service,
                                " from ApplicationContext using BeanName: " + serviceName);
                        continue; // skip to the next field
                    }
                    // else service == null
                    // now try to resolve using the ksb

                    final QName name = new QName(namespace, serviceName);

                    try {
                        SerializableProxyInvokationHandler invocationHandler = new SerializableProxyInvokationHandler();

                        invocationHandler.setServiceName(name);

                        service = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] { fieldType },
                                invocationHandler);

                        // now we have the service, try to inject it.
                        injectServiceReference(bean, beanName, field, service,
                                " from KSB using QName: " + name);

                    } catch (NullPointerException e1) {
                        log.warn("RiceResourceLoader is not configured/initialized properly.", e1);
                        // skip to the next field.
                        continue;
                    }

                } catch (Exception e) {
                    log.error("failed to lookup resource in GlobalResourceLoader (" + namespace + ", "
                            + serviceName + ")", e);
                    continue;
                }
            }

        }
    }

    // skip over any of the other post processors
    return false;
}