Example usage for org.springframework.util ReflectionUtils findField

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

Introduction

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

Prototype

@Nullable
public static Field findField(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Field field on the supplied Class with the supplied name .

Usage

From source file:com.ciphertool.genetics.PopulationTest.java

@Test
public void testSetTaskExecutor() {
    Population population = new Population();

    TaskExecutor taskExecutor = mock(TaskExecutor.class);
    population.setTaskExecutor(taskExecutor);

    Field taskExecutorField = ReflectionUtils.findField(Population.class, "taskExecutor");
    ReflectionUtils.makeAccessible(taskExecutorField);
    TaskExecutor taskExecutorFromObject = (TaskExecutor) ReflectionUtils.getField(taskExecutorField,
            population);/* w w w . j a va  2s  .  c om*/

    assertSame(taskExecutor, taskExecutorFromObject);
}

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

@Test
public void testSetStrategy() {
    GeneticAlgorithmStrategy strategyToSet = new GeneticAlgorithmStrategy();

    Population populationMock = mock(Population.class);
    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);
    NonUniformMutationAlgorithm mutationAlgorithmMock = mock(NonUniformMutationAlgorithm.class);
    SelectionAlgorithm selectionAlgorithmMock = mock(SelectionAlgorithm.class);
    FitnessEvaluator fitnessEvaluatorMock = mock(FitnessEvaluator.class);
    FitnessEvaluator knownSolutionFitnessEvaluatorMock = mock(FitnessEvaluator.class);
    Object geneticStructure = new Object();
    int lifeSpan = 10;
    boolean compareToKnownSolution = true;
    boolean mutateDuringCrossover = true;
    int maxMutationsPerIndividual = 5;

    strategyToSet.setGeneticStructure(geneticStructure);
    strategyToSet.setFitnessEvaluator(fitnessEvaluatorMock);
    strategyToSet.setLifespan(lifeSpan);
    strategyToSet.setKnownSolutionFitnessEvaluator(knownSolutionFitnessEvaluatorMock);
    strategyToSet.setCompareToKnownSolution(compareToKnownSolution);
    strategyToSet.setCrossoverAlgorithm(crossoverAlgorithmMock);
    strategyToSet.setMutationAlgorithm(mutationAlgorithmMock);
    strategyToSet.setMutateDuringCrossover(mutateDuringCrossover);
    strategyToSet.setMaxMutationsPerIndividual(maxMutationsPerIndividual);
    strategyToSet.setSelectionAlgorithm(selectionAlgorithmMock);

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

    Field strategyField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class, "strategy");
    ReflectionUtils.makeAccessible(strategyField);
    GeneticAlgorithmStrategy strategyFromObject = (GeneticAlgorithmStrategy) ReflectionUtils
            .getField(strategyField, multigenerationalGeneticAlgorithm);

    assertSame(strategyToSet, strategyFromObject);
    verify(populationMock, times(1)).setGeneticStructure(same(geneticStructure));
    verify(populationMock, times(1)).setFitnessEvaluator(same(fitnessEvaluatorMock));
    verify(populationMock, times(1)).setLifespan(eq(lifeSpan));
    verify(populationMock, times(1)).setKnownSolutionFitnessEvaluator(same(knownSolutionFitnessEvaluatorMock));
    verify(populationMock, times(1)).setCompareToKnownSolution(eq(compareToKnownSolution));
    verifyNoMoreInteractions(populationMock);

    verify(crossoverAlgorithmMock, times(1)).setMutationAlgorithm(same(mutationAlgorithmMock));
    verify(crossoverAlgorithmMock, times(1)).setMutateDuringCrossover(eq(mutateDuringCrossover));
    verifyNoMoreInteractions(crossoverAlgorithmMock);

    verify(mutationAlgorithmMock, times(1)).setMaxMutationsPerChromosome(eq(maxMutationsPerIndividual));
    verifyNoMoreInteractions(mutationAlgorithmMock);

    Field crossoverAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    CrossoverAlgorithm crossoverAlgorithmFromObject = (CrossoverAlgorithm) ReflectionUtils
            .getField(crossoverAlgorithmField, multigenerationalGeneticAlgorithm);

    assertSame(crossoverAlgorithmMock, crossoverAlgorithmFromObject);

    Field mutationAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "mutationAlgorithm");
    ReflectionUtils.makeAccessible(mutationAlgorithmField);
    MutationAlgorithm mutationAlgorithmFromObject = (MutationAlgorithm) ReflectionUtils
            .getField(mutationAlgorithmField, multigenerationalGeneticAlgorithm);

    assertSame(mutationAlgorithmMock, mutationAlgorithmFromObject);

    Field selectionAlgorithmField = ReflectionUtils.findField(MultigenerationalGeneticAlgorithm.class,
            "selectionAlgorithm");
    ReflectionUtils.makeAccessible(selectionAlgorithmField);
    SelectionAlgorithm selectionAlgorithmFromObject = (SelectionAlgorithm) ReflectionUtils
            .getField(selectionAlgorithmField, multigenerationalGeneticAlgorithm);

    assertSame(selectionAlgorithmMock, selectionAlgorithmFromObject);
}

From source file:com.github.marsbits.restfbmessenger.spring.boot.autoconfigure.MessengerAutoConfigurationTests.java

private Object getFieldValue(Object object, String name) {
    Field field = ReflectionUtils.findField(object.getClass(), name);
    ReflectionUtils.makeAccessible(field);
    return ReflectionUtils.getField(field, object);
}

From source file:com.ciphertool.sentencebuilder.etl.importers.FrequencyListImporterImplTest.java

@Test
public void testImportFrequencyList() {
    ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor());
    taskExecutorSpy.setCorePoolSize(4);/*  w  ww . j a v  a2s.  c o  m*/
    taskExecutorSpy.setMaxPoolSize(4);
    taskExecutorSpy.setQueueCapacity(100);
    taskExecutorSpy.setKeepAliveSeconds(1);
    taskExecutorSpy.setAllowCoreThreadTimeOut(true);
    taskExecutorSpy.initialize();

    FrequencyListImporterImpl frequencyListImporterImpl = new FrequencyListImporterImpl();
    frequencyListImporterImpl.setTaskExecutor(taskExecutorSpy);

    Field rowUpdateCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowUpdateCount");
    ReflectionUtils.makeAccessible(rowUpdateCountField);
    AtomicInteger rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowUpdateCountFromObject.intValue());

    Field rowInsertCountField = ReflectionUtils.findField(FrequencyListImporterImpl.class, "rowInsertCount");
    ReflectionUtils.makeAccessible(rowInsertCountField);
    AtomicInteger rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(0, rowInsertCountFromObject.intValue());

    WordDao wordDaoMock = mock(WordDao.class);
    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    int persistenceBatchSizeToSet = 2;
    int concurrencyBatchSizeToSet = 2;

    frequencyListImporterImpl.setWordDao(wordDaoMock);
    frequencyListImporterImpl.setPersistenceBatchSize(persistenceBatchSizeToSet);
    frequencyListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet);

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN), 100);
    Word word2 = new Word(new WordId("belden", PartOfSpeechType.NOUN), 200);
    Word word3 = new Word(new WordId("is", PartOfSpeechType.VERB_PARTICIPLE), 300);
    Word word4 = new Word(new WordId("awesome", PartOfSpeechType.ADJECTIVE), 400);
    List<Word> wordsToReturn = new ArrayList<Word>();
    wordsToReturn.add(word1);
    wordsToReturn.add(word2);
    wordsToReturn.add(word3);
    wordsToReturn.add(word4);
    FrequencyFileParser fileParserMock = mock(FrequencyFileParser.class);
    when(fileParserMock.parseFile()).thenReturn(wordsToReturn);

    frequencyListImporterImpl.setFileParser(fileParserMock);

    Word wordFromDatabase1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word wordFromDatabase2 = new Word(new WordId("belden", PartOfSpeechType.NOUN));

    when(wordDaoMock.insertBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.updateBatch(anyListOf(Word.class))).thenReturn(true);
    when(wordDaoMock.findByWordString(eq("george"))).thenReturn(Arrays.asList(wordFromDatabase1));
    when(wordDaoMock.findByWordString(eq("belden"))).thenReturn(Arrays.asList(wordFromDatabase2));
    when(wordDaoMock.findByWordString(eq("is"))).thenReturn(null);
    when(wordDaoMock.findByWordString(eq("awesome"))).thenReturn(null);

    frequencyListImporterImpl.importFrequencyList();

    assertEquals(100, wordFromDatabase1.getFrequencyWeight());
    assertEquals(200, wordFromDatabase2.getFrequencyWeight());

    rowUpdateCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowUpdateCountField,
            frequencyListImporterImpl);
    rowInsertCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowInsertCountField,
            frequencyListImporterImpl);

    assertEquals(2, rowUpdateCountFromObject.intValue());
    assertEquals(2, rowInsertCountFromObject.intValue());
    verify(wordDaoMock, times(1)).insertBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(1)).updateBatch(anyListOf(Word.class));
    verify(wordDaoMock, times(4)).findByWordString(anyString());
    verify(taskExecutorSpy, times(2)).execute(any(Runnable.class));
}

From source file:com.ciphertool.zodiacengine.fitness.AbstractSolutionEvaluatorBaseTest.java

@Test
public void testClearHasMatchValues_NullSolution() {
    ConcreteSolutionEvaluatorBase abstractSolutionEvaluatorBase = new ConcreteSolutionEvaluatorBase();

    Field logField = ReflectionUtils.findField(ConcreteSolutionEvaluatorBase.class, "log");
    Logger mockLogger = mock(Logger.class);
    ReflectionUtils.makeAccessible(logField);
    ReflectionUtils.setField(logField, abstractSolutionEvaluatorBase, mockLogger);

    abstractSolutionEvaluatorBase.clearHasMatchValues(null);

    verify(mockLogger, times(1))/*from w w  w. j a  v  a 2  s .  c o  m*/
            .warn("Attempted to clear hasMatch values, but the SolutionChromosome was null.  Returning early.");
}

From source file:com.ciphertool.genetics.PopulationTest.java

@Test
public void testSetSelector() {
    Population population = new Population();

    Selector selector = mock(Selector.class);
    population.setSelector(selector);//from   w  ww.j a v  a  2 s  .  c om

    Field selectorField = ReflectionUtils.findField(Population.class, "selector");
    ReflectionUtils.makeAccessible(selectorField);
    Selector selectorFromObject = (Selector) ReflectionUtils.getField(selectorField, population);

    assertSame(selector, selectorFromObject);
}

From source file:jndi.view.JndiView.java

/**
 * @param entry/*from   w w  w  .  j a  va 2s. co  m*/
 *        the {@link JndiEntry} we're working on
 * @param obj
 *        the Object we're inspecting
 */
private void inspectJndiNamingObjectProxy(final JndiEntry entry, final Object obj) {
    final Field f = ReflectionUtils.findField(obj.getClass(), "intfName");
    if (f != null) {
        final Object v = Reflection.getField(obj, f);
        logger.finest("intfName: " + v);
        entry.setTargetClassName(v.toString());
    }
}

From source file:org.terasoluna.gfw.common.codelist.JdbcCodeListTest.java

/**
 * In case LazyInit is set to true/* ww  w .  ja  va2 s  .  c  om*/
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@Test
public void testAfterPropertiesSet02() throws Exception {
    // create target
    JdbcCodeList jdbcCodeList = new JdbcCodeList();

    // setup parameters\
    jdbcCodeList.setDataSource(dataSource);
    jdbcCodeList.setLazyInit(true);
    jdbcCodeList.setLabelColumn("code_name");
    jdbcCodeList.setValueColumn("code_id");
    jdbcCodeList.setQuerySql("Select code_id, code_name from codelist");

    // fetch exposed map for the first time

    Field f = ReflectionUtils.findField(JdbcCodeList.class, "exposedMap");
    ReflectionUtils.makeAccessible(f);
    Map<String, String> exposedMapFirstFetch = (Map<String, String>) f.get(jdbcCodeList);

    // assert
    assertNull(exposedMapFirstFetch);

    // run
    jdbcCodeList.afterPropertiesSet();

    // assert again
    assertNull(exposedMapFirstFetch);
}

From source file:com.github.dactiv.fear.commons.Apis.java

@Override
public void afterPropertiesSet() throws Exception {

    PropertySourcesPlaceholderConfigurer configurer = null;
    PropertySources propertySources = null;
    try {//  ww w . j  a v a2s.c om
        configurer = applicationContext.getBean(PropertySourcesPlaceholderConfigurer.class);
        propertySources = configurer.getAppliedPropertySources();
    } catch (Exception e) {
        LOGGER.warn("install " + PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME
                + " error", e);
    }

    if (propertySources == null) {
        return;
    }

    Field field = ReflectionUtils.findField(configurer.getClass(), "environment");
    field.setAccessible(Boolean.TRUE);
    environment = (Environment) field.get(configurer);
    if (environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment ce = (ConfigurableEnvironment) environment;
        MutablePropertySources sources = ce.getPropertySources();
        PropertySource<?> ps = propertySources
                .get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME);
        sources.addFirst(ps);
    }
}

From source file:com.ciphertool.genetics.PopulationTest.java

@Test
public void testSetLifespan() {
    Population population = new Population();

    int lifespanToSet = 25;
    population.setLifespan(lifespanToSet);

    Field lifespanField = ReflectionUtils.findField(Population.class, "lifespan");
    ReflectionUtils.makeAccessible(lifespanField);
    int lifespanFromObject = (int) ReflectionUtils.getField(lifespanField, population);

    assertSame(lifespanToSet, lifespanFromObject);
}