Example usage for org.springframework.util ReflectionUtils setField

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

Introduction

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

Prototype

public static void setField(Field field, @Nullable Object target, @Nullable Object value) 

Source Link

Document

Set the field represented by the supplied Field field object on the specified Object target object to the specified value .

Usage

From source file:com.ciphertool.genetics.algorithms.MultigenerationalGeneticAlgorithmTest.java

@Test
public void testSpawnInitialPopulation() {
    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();
    int populationSize = 100;
    strategyToSet.setPopulationSize(populationSize);

    Population populationMock = mock(Population.class);

    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();
    multigenerationalGeneticAlgorithm.setPopulation(populationMock);

    Field strategyField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "strategy");
    ReflectionUtils.makeAccessible(strategyField);
    ReflectionUtils.setField(strategyField, multigenerationalGeneticAlgorithm, strategyToSet);

    multigenerationalGeneticAlgorithm.spawnInitialPopulation();

    verify(populationMock, times(1)).clearIndividuals();
    verify(populationMock, times(1)).breed(eq(populationSize));
    verify(populationMock, times(1)).evaluateFitness(null);
    verify(populationMock, times(1)).size();
    verifyNoMoreInteractions(populationMock);
}

From source file:com.ciphertool.genetics.algorithms.MultigenerationalGeneticAlgorithmTest.java

@Test
public void testPersistStatistics() {
    ExecutionStatisticsDao executionStatisticsDaoToSet = mock(ExecutionStatisticsDao.class);

    MultigenerationalGeneticAlgorithm multigenerationalGeneticAlgorithm = new MultigenerationalGeneticAlgorithm();
    multigenerationalGeneticAlgorithm.setExecutionStatisticsDao(executionStatisticsDaoToSet);

    ExecutionStatistics executionStatistics = new ExecutionStatistics();
    Field executionStatisticsField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "executionStatistics");
    ReflectionUtils.makeAccessible(executionStatisticsField);
    ReflectionUtils.setField(executionStatisticsField, multigenerationalGeneticAlgorithm, executionStatistics);

    multigenerationalGeneticAlgorithm.persistStatistics();

    verify(executionStatisticsDaoToSet, times(1)).insert(same(executionStatistics));
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

@SuppressWarnings("unchecked")
public <T> T objectFrom(final Result result, final Class<T> hBasePersistanceClass) {
    if (!annotatedClassToAnnotatedHBaseRowKey.containsKey(hBasePersistanceClass)) {
        throw new IllegalArgumentException(
                "Class passed to objectFrom(final Result result, final Class<T> hBasePersistanceClass) must be a correct HBase persistable class! If this class is annotaed with @HBasePersistance please see startup errors for why it might have been excluded. ");
    }//  ww w. ja va  2 s .c o m
    if (result.isEmpty()) {
        return null;
    }
    /*
     * Create new instance of our target class
     */
    final T type = Whitebox.newInstance(hBasePersistanceClass);
    final NavigableMap<byte[], NavigableMap<byte[], byte[]>> columnFamilyResultMap = result.getNoVersionMap();
    /*
     * Map results to fields annotated with @HBaseField
     */
    for (final Field field : annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, type,
                TypeHandler.getTypedValue(field.getType(),
                        columnFamilyResultMap.get(columnFamilyNameFromHBaseFieldAnnotatedField(field))
                                .remove(Bytes.toBytes(field.getName()))));
    }
    /*
     * Map results to fields annotated with @HBaseObjectField
     */
    for (final Field field : annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod
            .get(hBasePersistanceClass).keySet()) {
        ReflectionUtils.makeAccessible(field);
        try {
            /*
             * We may purposely not want to populate certain fields by not including the column family
             */
            final byte[] columnFamily = columnFamilyNameFromHBaseObjectFieldAnnotatedField(field);
            if (columnFamilyResultMap.containsKey(columnFamily)) {
                ReflectionUtils.setField(field, type,
                        field.getAnnotation(HBaseObjectField.class).serializationStategy().deserialize(
                                columnFamilyResultMap.get(columnFamily).remove(Bytes.toBytes(field.getName())),
                                field));
            }
        } catch (Exception e) {
            /*
             *  We serialized this we should be able to de-serialize it. Did the serialization change?
             *  
             *  TODO: store serialization type so we can better guarantee de-serialization
             */
            LOG.error("Could not deserialize " + field.getName() + " for family map name: "
                    + columnFamilyNameFromHBaseObjectFieldAnnotatedField(field)
                    + " Did the serialization (KRYO/JSON) OR field type change from when you serialized the object?",
                    e);
        }
    }
    /*
     * Map results to fields annotated with @HBaseMapField
     */
    mapFieldBlock: {
        if (annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                .get(hBasePersistanceClass) != null) {
            final Field field = annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod
                    .get(hBasePersistanceClass).keySet().iterator().next();
            Map<String, String> map;
            if (field.getType().equals(Map.class)) {
                /*
                 *  If the object just calls for a Map give them a TreeMap();
                 */
                map = new TreeMap<String, String>();
            } else {
                /*
                 *  else try to create an instance of the Map class they are using
                 */
                try {
                    map = (Map<String, String>) Whitebox.getConstructor(field.getType())
                            .newInstance((Object[]) null);
                } catch (Exception e) {
                    /*
                     *  Done our best to guard against this but still possible
                     */
                    LOG.error("Could not create new instance of map.", e);
                    break mapFieldBlock;
                }
            }
            for (final Entry<byte[], byte[]> entry : columnFamilyResultMap
                    .get(columnFamilyNameFromHBaseMapFieldAnnotatedField(field)).entrySet()) {
                map.put(Bytes.toString(entry.getKey()), Bytes.toString(entry.getValue()));
            }
            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.setField(field, type, map);
        }
    }

    return type;

}

From source file:com.opendesign.utils.CmnUtil.java

/**
 *  vo ? ?? / ? ./* ww w  . j a v  a2  s . c om*/
 * 
 * @param vo
 */
public static void setCmnDate(Object vo) {
    String curDateStr = Day.getCurrentDateString("yyyyMMddHHmm");
    Class<?> clazz = vo.getClass();
    // ??
    Field regTimeField = ReflectionUtils.findField(clazz, "registerTime");
    if (regTimeField != null) {
        ReflectionUtils.makeAccessible(regTimeField);
        ReflectionUtils.setField(regTimeField, vo, curDateStr);
    }
    // ?
    Field updTimeField = ReflectionUtils.findField(clazz, "updateTime");
    if (updTimeField != null) {
        ReflectionUtils.makeAccessible(updTimeField);
        ReflectionUtils.setField(updTimeField, vo, curDateStr);
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * client to server: html enter  /*from   www.  ja v a  2  s.  co  m*/
 * @param vo
 * @param fieldName
 */
public static void handleHtmlEnterRN2BR(Object vo, String fieldName) {
    if (vo == null) {
        return;
    }

    Class<?> clazz = vo.getClass();
    // 
    Field aField = ReflectionUtils.findField(clazz, fieldName);
    if (aField != null) {
        ReflectionUtils.makeAccessible(aField);
        String contents = (String) ReflectionUtils.getField(aField, vo);
        contents = handleHtmlEnterRN2BR(contents);
        ReflectionUtils.setField(aField, vo, contents);
    }
}

From source file:com.opendesign.utils.CmnUtil.java

/**
 * server to client: html enter  //from w  ww  . j a  va2  s  . co m
 * @param vo
 * @param fieldName
 */
public static void handleHtmlEnterBR2RN(Object vo, String fieldName) {
    if (vo == null) {
        return;
    }

    Class<?> clazz = vo.getClass();
    // 
    Field aField = ReflectionUtils.findField(clazz, fieldName);
    if (aField != null) {
        ReflectionUtils.makeAccessible(aField);
        String contents = (String) ReflectionUtils.getField(aField, vo);
        contents = handleHtmlEnterBR2RN(contents);
        ReflectionUtils.setField(aField, vo, contents);
    }
}

From source file:com.thoughtworks.go.server.database.SqlSessionFactoryBean.java

private SqlSessionFactory buildSqlSessionFactory() throws IOException {
    SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();

    Configuration baseConfiguration = new XMLConfigBuilder(configLocation.getInputStream()).parse();

    String ibatisConfigXmlLocation = databaseStrategy.getIbatisConfigXmlLocation();
    if (isNotBlank(ibatisConfigXmlLocation)) {
        XMLConfigBuilder builder = new XMLConfigBuilder(
                new ClassPathResource(ibatisConfigXmlLocation).getInputStream());

        // hacky way to "inject" a previous configuration
        Field configurationField = ReflectionUtils.findField(XMLConfigBuilder.class, "configuration");
        ReflectionUtils.makeAccessible(configurationField);
        ReflectionUtils.setField(configurationField, builder, baseConfiguration);

        baseConfiguration = builder.parse();
    }/*w w w  .j  a  v  a 2 s . c om*/

    baseConfiguration.setEnvironment(new Environment(getClass().getSimpleName(),
            new SpringManagedTransactionFactory(), this.dataSource));

    return factoryBuilder.build(baseConfiguration);
}

From source file:io.servicecomb.springboot.starter.configuration.CseAutoConfiguration.java

private static void setStatic(Class<?> type, String name, Object value) {
    // Hack a private static field
    Field field = ReflectionUtils.findField(type, name);
    ReflectionUtils.makeAccessible(field);
    ReflectionUtils.setField(field, null, value);
}

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
                    + "'");
        }/*from w ww.  j  a va  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  va  2 s .c  o  m*/

    // 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);
}