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.zodiacengine.fitness.AbstractSolutionEvaluatorBaseTest.java

@SuppressWarnings("unchecked")
@Test/*from   w w  w .  java  2s  . com*/
public void testSetGeneticStructure() {
    ConcreteSolutionEvaluatorBase abstractSolutionEvaluatorBase = new ConcreteSolutionEvaluatorBase();

    abstractSolutionEvaluatorBase.setGeneticStructure(simpleCipher);

    Field cipherField = ReflectionUtils.findField(ConcreteSolutionEvaluatorBase.class, "cipher");
    ReflectionUtils.makeAccessible(cipherField);
    Cipher cipherFromObject = (Cipher) ReflectionUtils.getField(cipherField, abstractSolutionEvaluatorBase);

    assertEquals(simpleCipher, cipherFromObject);

    Field ciphertextKeyField = ReflectionUtils.findField(ConcreteSolutionEvaluatorBase.class, "ciphertextKey");
    ReflectionUtils.makeAccessible(ciphertextKeyField);
    HashMap<String, List<Ciphertext>> ciphertextKeyFromObject = (HashMap<String, List<Ciphertext>>) ReflectionUtils
            .getField(ciphertextKeyField, abstractSolutionEvaluatorBase);

    assertNotNull(ciphertextKeyFromObject);
}

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

private Field findField(String propertyName) {
    return ReflectionUtils.findField(domainType, propertyName);
}

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

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

    FitnessEvaluator knownSolutionFitnessEvaluatorMock = mock(FitnessEvaluator.class);
    when(knownSolutionFitnessEvaluatorMock.evaluate(any(Chromosome.class))).thenReturn(DEFAULT_FITNESS_VALUE);
    population.setKnownSolutionFitnessEvaluator(knownSolutionFitnessEvaluatorMock);

    Field knownSolutionFitnessEvaluatorField = ReflectionUtils.findField(Population.class,
            "knownSolutionFitnessEvaluator");
    ReflectionUtils.makeAccessible(knownSolutionFitnessEvaluatorField);
    FitnessEvaluator knownSolutionFitnessEvaluatorFromObject = (FitnessEvaluator) ReflectionUtils
            .getField(knownSolutionFitnessEvaluatorField, population);

    assertSame(knownSolutionFitnessEvaluatorMock, knownSolutionFitnessEvaluatorFromObject);
}

From source file:py.una.pol.karaku.dao.search.SearchHelper.java

/**
 * Retorna la informacin relacionada a un Field definido por una propiedad
 * (con un formato separado por puntos).
 * <p>//from  w  w  w  .  ja  va  2 s.co m
 * Por ejemplo, si invocamos de la siguiente manera:
 * 
 * <pre>
 *    class Pais {
 *       ...
 *       Set{@literal <}Departamento> departamentos;
 * 
 *       ...
 *    }
 * 
 *    class Departamento {
 *       ...
 *       Set{@literal <}Ciudad> ciudades;
 * 
 *       Set etnias;
 * 
 *       Pais pais;
 *       ...
 *    }
 * 
 *    class Ciudad {
 *       ...
 * 
 *       Departamento departamento;
 *       ...
 *    }
 * 
 * 1. Y invocamos de la siguiente manera:
 * 
 *    fi = getFieldInfo(Ciudad.class, "departamento.pais");
 *    fi.getField() ==> Pais.class
 *    fi.isCollection() == > <code>false</code>
 * 
 * 2. El siguiente ejemplo, es cuando se encuentra una {@link Collection}
 * 
 *    fi = getFieldInfo(Ciudad.class, "departamento.etnias");
 *    fi.getField() ==> Etnia.class
 *    fi.isCollection() == > <code>true</code>
 * </pre>
 * 
 * <p>
 * TODO ver para meter en una clase de utilidad
 * </p>
 * 
 * @param root
 *            {@link Class} que sirve de base para buscar la propiedad
 * @param property
 *            cadena separada por <code>.</code> (puntos) que sirve para
 *            recorrer a travs del objeto y obtener la propiedad deseada.
 * @return {@link FieldInfo} con la informacin posible que se ha
 *         conseguido.
 * @throw {@link KarakuRuntimeException} si no encuentra el field o no es
 *        accesible.
 */
public static FieldInfo getFieldInfo(@NotNull Class<?> root, @NotNull String property) {

    try {
        String[] splited = property.split(Pattern.quote("."));
        String cProperty;
        Class<?> cClass = root;
        Field toRet = null;
        boolean collectionFound = false;
        for (String element : splited) {
            cProperty = element;
            toRet = ReflectionUtils.findField(cClass, cProperty);
            if (toRet == null) {
                throw new KarakuRuntimeException(
                        "Field: " + cProperty + " not found. (Full path: " + property + ")");
            }
            cClass = toRet.getType();
            // Si tenemos una lista, buscar el tipo de la lista.
            if (Collection.class.isAssignableFrom(cClass)) {
                cClass = GenericCollectionTypeResolver.getCollectionFieldType(toRet);
            }
            // TODO add expansion if found a @Display in the last field
            // Ejemplo: pais.departamento, puede seguir siendo explotado
            // si departamento tiene un DisplayName
        }
        return new FieldInfo(toRet, collectionFound);
    } catch (SecurityException e) {
        throw new KarakuRuntimeException(
                "Field not accessible: " + property + " in class " + root.getSimpleName(), e);
    }
}

From source file:py.una.pol.karaku.util.ELHelper.java

private static Field getFieldFromCGEnhancedClass(String name, Class<?> clazz) {

    Class<?> real = clazz.getSuperclass();
    return ReflectionUtils.findField(real, name);
}

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

@Test
public void testImportWordList_LeftoversFromBatch() {
    ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor());
    taskExecutorSpy.setCorePoolSize(4);/*ww  w. ja  va  2 s.c  o  m*/
    taskExecutorSpy.setMaxPoolSize(4);
    taskExecutorSpy.setQueueCapacity(100);
    taskExecutorSpy.setKeepAliveSeconds(1);
    taskExecutorSpy.setAllowCoreThreadTimeOut(true);
    taskExecutorSpy.initialize();

    WordListImporterImpl wordListImporterImpl = new WordListImporterImpl();
    wordListImporterImpl.setTaskExecutor(taskExecutorSpy);

    Field rowCountField = ReflectionUtils.findField(WordListImporterImpl.class, "rowCount");
    ReflectionUtils.makeAccessible(rowCountField);
    AtomicInteger rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField,
            wordListImporterImpl);

    assertEquals(0, rowCountFromObject.intValue());

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

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

    Word word1 = new Word(new WordId("george", PartOfSpeechType.NOUN));
    Word word2 = new Word(new WordId("elmer", PartOfSpeechType.NOUN));
    Word word3 = new Word(new WordId("belden", PartOfSpeechType.NOUN));
    List<Word> wordsToReturn = new ArrayList<Word>();
    wordsToReturn.add(word1);
    wordsToReturn.add(word2);
    wordsToReturn.add(word3);
    PartOfSpeechFileParser fileParserMock = mock(PartOfSpeechFileParser.class);
    when(fileParserMock.parseFile()).thenReturn(wordsToReturn);

    wordListImporterImpl.setFileParser(fileParserMock);

    wordListImporterImpl.importWordList();

    rowCountFromObject = (AtomicInteger) ReflectionUtils.getField(rowCountField, wordListImporterImpl);

    assertEquals(3, rowCountFromObject.intValue());
    verify(wordDaoMock, times(2)).insertBatch(anyListOf(Word.class));
    verify(taskExecutorSpy, times(2)).execute(any(Runnable.class));
}

From source file:de.extra.client.core.builder.impl.MessageBuilderLocatorTest.java

/**
 * Setzt eine Value ber ReflectionUtils//from  www  .  ja v  a  2s. c o m
 * 
 * @param messageBuilderLocator
 * @param rootElementsBuilderMap
 * @param string
 */
private void injectValue(final Object object, final Object value, final String fieldName) {
    final Field fieldToSet = ReflectionUtils.findField(object.getClass(), fieldName);
    ReflectionUtils.makeAccessible(fieldToSet);
    ReflectionUtils.setField(fieldToSet, object, value);
}

From source file:com.ciphertool.zodiacengine.service.GeneticCipherSolutionServiceTest.java

@Test
public void testBegin_DebugMode() throws IOException {
    GeneticCipherSolutionService geneticCipherSolutionService = new GeneticCipherSolutionService();

    GeneticAlgorithm geneticAlgorithm = mock(GeneticAlgorithm.class);

    Population population = new Population();
    SolutionChromosome solutionChromosome = new SolutionChromosome();
    solutionChromosome.setEvaluationNeeded(false);
    population.addIndividual(solutionChromosome);
    when(geneticAlgorithm.getPopulation()).thenReturn(population);

    geneticCipherSolutionService.setGeneticAlgorithm(geneticAlgorithm);

    GenericCallback genericCallbackMock = mock(GenericCallback.class);

    GeneticAlgorithmStrategy geneticAlgorithmStrategy = new GeneticAlgorithmStrategy();

    Runtime runtimeMock = mock(Runtime.class);

    Field runtimeField = ReflectionUtils.findField(GeneticCipherSolutionService.class, "runtime");
    ReflectionUtils.makeAccessible(runtimeField);
    ReflectionUtils.setField(runtimeField, geneticCipherSolutionService, runtimeMock);

    String[] commandsBefore = { "command3", "command4" };
    geneticCipherSolutionService.setCommandsBefore(commandsBefore);

    assertFalse(geneticCipherSolutionService.isRunning());
    geneticCipherSolutionService.begin(geneticAlgorithmStrategy, genericCallbackMock, true);
    assertTrue(geneticCipherSolutionService.isRunning());

    verify(runtimeMock, times(1)).exec(eq("command3"));
    verify(runtimeMock, times(1)).exec(eq("command4"));
    verifyNoMoreInteractions(runtimeMock);

    verifyZeroInteractions(genericCallbackMock);

    verify(geneticAlgorithm, times(1)).initialize();
    verify(geneticAlgorithm, times(1)).getPopulation();
    verify(geneticAlgorithm, times(1)).proceedWithNextGeneration();

    verify(geneticAlgorithm, times(1)).setStrategy(same(geneticAlgorithmStrategy));
}

From source file:com.github.gavlyukovskiy.boot.jdbc.decorator.flexypool.FlexyPoolConfigurationTests.java

@SuppressWarnings("unchecked")
private <T extends DataSource> FlexyPoolDataSource<T> assertDataSourceOfType(DataSource dataSource,
        Class<T> realDataSourceClass) {
    assertThat(dataSource).isInstanceOf(DecoratedDataSource.class);
    DataSource decoratedDataSource = ((DecoratedDataSource) dataSource).getDecoratedDataSource();
    assertThat(decoratedDataSource).isInstanceOf(FlexyPoolDataSource.class);
    Field field = ReflectionUtils.findField(FlexyPoolDataSource.class, "targetDataSource");
    ReflectionUtils.makeAccessible(field);
    Object targetDataSource = ReflectionUtils.getField(field, decoratedDataSource);
    assertThat(targetDataSource).isInstanceOf(realDataSourceClass);
    return (FlexyPoolDataSource<T>) decoratedDataSource;
}

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

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

    Boolean compareToKnownSolution = true;
    population.setCompareToKnownSolution(compareToKnownSolution);

    Field compareToKnownSolutionField = ReflectionUtils.findField(Population.class, "compareToKnownSolution");
    ReflectionUtils.makeAccessible(compareToKnownSolutionField);
    Boolean compareToKnownSolutionFromObject = (Boolean) ReflectionUtils.getField(compareToKnownSolutionField,
            population);/*ww  w  . j  ava  2 s  .  c om*/

    assertSame(compareToKnownSolution, compareToKnownSolutionFromObject);
}