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.jdal.annotation.AnnotatedElementAccessor.java

/**
 * Try to set a value on AnnotatedElement.
 * @param element the annotated element.
 * @param value value to set./*from  ww w  . j a v  a2 s .  c om*/
 */
public static void setValue(AnnotatedElement element, Object target, Object value) {
    if (element instanceof Field) {
        Field field = (Field) element;
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, target, value);
    } else if (element instanceof Method) {
        Method method = (Method) element;
        try {
            method.invoke(target, new Object[] { value });
        } catch (Exception e) {
            log.error("Cannot set value on method [" + method.toString() + "]");
        }
    }
}

From source file:org.web4thejob.orm.serial.MyXStreamMarshaller.java

private void customizeMappers(XStream xstream) {
    // huge HACK since there seems to be no direct way of adding
    // HibernateMapper
    final Converter reflectionConverter = xstream.getConverterLookup().lookupConverterForType(Entity.class);

    if (!ReflectionConverter.class.isInstance(reflectionConverter))
        throw new IllegalStateException("expected " + ReflectionConverter.class.getName() + " but got "
                + reflectionConverter.getClass().getName());

    final Field field = ReflectionUtils.findField(ReflectionConverter.class, "mapper");
    ReflectionUtils.makeAccessible(field);
    CachingMapper mapper = (CachingMapper) ReflectionUtils.getField(field, reflectionConverter);
    mapper = new CachingMapper(new MyHibernateMapper(mapper));
    ReflectionUtils.setField(field, reflectionConverter, mapper);
}

From source file:com.greenline.hrs.admin.web.war.conf.InjectBeanPostProcessor.java

private void injectPropertyToBean(final Object bean) {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        @Override/*from   w  w  w  .  jav  a  2  s .  co m*/
        public void doWith(Field field) throws IllegalAccessException {
            InjectingProperty annotation = field.getAnnotation(InjectingProperty.class);
            if (annotation != null) {
                Object strValue = propertyConfigurer.getProperty(annotation.value());
                if (null != strValue) {
                    Object value = typeConverter.convertIfNecessary(strValue, field.getType());
                    ReflectionUtils.makeAccessible(field);
                    if (Modifier.isStatic(field.getModifiers())) {
                        field.set(null, value);
                    } else {
                        field.set(bean, value);
                    }
                }
            }
        }
    });
}

From source file:com.ryantenney.metrics.spring.MetricAnnotationBeanPostProcessor.java

@Override
protected void withField(Object bean, String beanName, Class<?> targetClass, Field field) {
    final Metric annotation = field.getAnnotation(Metric.class);
    final String metricName = Util.forMetricField(targetClass, field, annotation);

    final Class<?> type = field.getType();
    if (!com.codahale.metrics.Metric.class.isAssignableFrom(type)) {
        throw new IllegalArgumentException("Field " + targetClass.getCanonicalName() + "." + field.getName()
                + " must be a subtype of " + com.codahale.metrics.Metric.class.getCanonicalName());
    }/*from   w w w. j  a  va2  s .  co  m*/

    ReflectionUtils.makeAccessible(field);

    // Get the value of the field annotated with @Metric
    com.codahale.metrics.Metric metric = (com.codahale.metrics.Metric) ReflectionUtils.getField(field, bean);

    if (metric == null) {
        // If null, create a metric of the appropriate type and inject it
        metric = getMetric(metrics, type, metricName);
        ReflectionUtils.setField(field, bean, metric);
        LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                field.getName());
    } else {
        // If non-null, register that instance of the metric
        try {
            // Attempt to register that instance of the metric
            metrics.register(metricName, metric);
            LOG.debug("Registered metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        } catch (IllegalArgumentException ex1) {
            // A metric is already registered under that name
            // (Cannot determine the cause without parsing the Exception's message)
            try {
                metric = getMetric(metrics, type, metricName);
                ReflectionUtils.setField(field, bean, metric);
                LOG.debug("Injected metric {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                        field.getName());
            } catch (IllegalArgumentException ex2) {
                // A metric of a different type is already registered under that name
                throw new IllegalArgumentException("Error injecting metric for field "
                        + targetClass.getCanonicalName() + "." + field.getName(), ex2);
            }
        }
    }
}

From source file:com.ciphertool.genetics.algorithms.mutation.ConservativeMutationAlgorithmTest.java

@BeforeClass
public static void setUp() {
    conservativeMutationAlgorithm = new ConservativeMutationAlgorithm();

    geneDaoMock = mock(VariableLengthGeneDao.class);
    conservativeMutationAlgorithm.setGeneDao(geneDaoMock);

    logMock = mock(Logger.class);
    Field logField = ReflectionUtils.findField(ConservativeMutationAlgorithm.class, "log");
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, conservativeMutationAlgorithm, logMock);
}

From source file:com.ciphertool.genetics.algorithms.mutation.SingleSequenceMutationAlgorithmTest.java

@BeforeClass
public static void setUp() {
    singleSequenceMutationAlgorithm = new SingleSequenceMutationAlgorithm();

    sequenceDaoMock = mock(SequenceDao.class);
    singleSequenceMutationAlgorithm.setSequenceDao(sequenceDaoMock);

    logMock = mock(Logger.class);
    Field logField = ReflectionUtils.findField(SingleSequenceMutationAlgorithm.class, "log");
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, singleSequenceMutationAlgorithm, logMock);
}

From source file:com.ryantenney.metrics.spring.GaugeAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) {
    final Class<?> targetClass = AopUtils.getTargetClass(bean);

    ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
        @Override//  www .j  a v  a 2 s .  co  m
        public void doWith(final Field field) throws IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            final Gauge annotation = field.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, field, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    Object value = ReflectionUtils.getField(field, bean);
                    if (value instanceof com.codahale.metrics.Gauge) {
                        value = ((com.codahale.metrics.Gauge<?>) value).getValue();
                    }
                    return value;
                }
            });

            LOG.debug("Created gauge {} for field {}.{}", metricName, targetClass.getCanonicalName(),
                    field.getName());
        }
    }, FILTER);

    ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
        @Override
        public void doWith(final Method method) throws IllegalAccessException {
            if (method.getParameterTypes().length > 0) {
                throw new IllegalStateException(
                        "Method " + method.getName() + " is annotated with @Gauge but requires parameters.");
            }

            final Gauge annotation = method.getAnnotation(Gauge.class);
            final String metricName = Util.forGauge(targetClass, method, annotation);

            metrics.register(metricName, new com.codahale.metrics.Gauge<Object>() {
                @Override
                public Object getValue() {
                    return ReflectionUtils.invokeMethod(method, bean);
                }
            });

            LOG.debug("Created gauge {} for method {}.{}", metricName, targetClass.getCanonicalName(),
                    method.getName());
        }
    }, FILTER);

    return bean;
}

From source file:com.ciphertool.zodiacengine.dao.CipherDaoTest.java

@Test
public void testSetMongoTemplate() {
    CipherDao cipherDao = new CipherDao();
    cipherDao.setMongoTemplate(mongoTemplateMock);

    Field mongoOperationsField = ReflectionUtils.findField(CipherDao.class, "mongoOperations");
    ReflectionUtils.makeAccessible(mongoOperationsField);
    MongoOperations mongoOperationsFromObject = (MongoOperations) ReflectionUtils.getField(mongoOperationsField,
            cipherDao);/*from  w  w  w. j  a  va2 s.  co m*/

    assertSame(mongoTemplateMock, mongoOperationsFromObject);
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyMethodExtractorImpl.java

/**
 * Creates a new {@link DynamoDBHashAndRangeKeyMethodExtractor} for the given domain type.
 *
 * @param idType//from ww  w.j av a  2 s  . c  o  m
 *            must not be {@literal null}.
 */
public DynamoDBHashAndRangeKeyMethodExtractorImpl(final Class<T> idType) {

    Assert.notNull(idType, "Id type must not be null!");
    this.idType = idType;
    ReflectionUtils.doWithMethods(idType, new MethodCallback() {
        @Override
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBHashKey.class) != null) {
                Assert.isNull(hashKeyMethod,
                        "Multiple methods annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(method);
                hashKeyMethod = method;
            }
        }
    });
    ReflectionUtils.doWithFields(idType, new FieldCallback() {
        @Override
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBHashKey.class) != null) {
                Assert.isNull(hashKeyField,
                        "Multiple fields annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(field);

                hashKeyField = field;
            }
        }
    });
    ReflectionUtils.doWithMethods(idType, new MethodCallback() {
        @Override
        public void doWith(Method method) {
            if (method.getAnnotation(DynamoDBRangeKey.class) != null) {
                Assert.isNull(rangeKeyMethod, "Multiple methods annotated by @DynamoDBRangeKey within type "
                        + idType.getName() + "!");
                ReflectionUtils.makeAccessible(method);
                rangeKeyMethod = method;
            }
        }
    });
    ReflectionUtils.doWithFields(idType, new FieldCallback() {
        @Override
        public void doWith(Field field) {
            if (field.getAnnotation(DynamoDBRangeKey.class) != null) {
                Assert.isNull(rangeKeyField,
                        "Multiple fields annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
                ReflectionUtils.makeAccessible(field);
                rangeKeyField = field;
            }
        }
    });
    if (hashKeyMethod == null && hashKeyField == null) {
        throw new IllegalArgumentException(
                "No method or field annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
    }
    if (rangeKeyMethod == null && rangeKeyField == null) {
        throw new IllegalArgumentException(
                "No method or field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
    }
    if (hashKeyMethod != null && hashKeyField != null) {
        throw new IllegalArgumentException(
                "Both method and field annotated by @DynamoDBHashKey within type " + idType.getName() + "!");
    }
    if (rangeKeyMethod != null && rangeKeyField != null) {
        throw new IllegalArgumentException(
                "Both method and field annotated by @DynamoDBRangeKey within type " + idType.getName() + "!");
    }
}

From source file:com.ace.erp.common.inject.support.InjectBaseDependencyHelper.java

/**
 * ??/*from   w  w  w .  j a v a2  s. c  om*/
 *
 * @param target
 * @param annotation
 */
private static Set<Object> findDependencies(final Object target, final Class<? extends Annotation> annotation) {

    final Set<Object> candidates = Sets.newHashSet();

    ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() {
        @Override
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);
            Object obj = ReflectionUtils.getField(field, target);
            candidates.add(obj);
        }
    }, new ReflectionUtils.FieldFilter() {
        @Override
        public boolean matches(Field field) {
            return field.isAnnotationPresent(annotation);
        }
    });

    ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(method);
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            candidates.add(ReflectionUtils.invokeMethod(descriptor.getReadMethod(), target));
        }
    }, new ReflectionUtils.MethodFilter() {
        @Override
        public boolean matches(Method method) {
            boolean hasAnnotation = false;
            hasAnnotation = method.isAnnotationPresent(annotation);
            if (!hasAnnotation) {
                return false;
            }

            boolean hasReadMethod = false;
            PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method);
            hasReadMethod = descriptor != null && descriptor.getReadMethod() != null;

            if (!hasReadMethod) {
                return false;
            }

            return true;
        }
    });

    return candidates;
}