Example usage for org.springframework.util ReflectionUtils getField

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

Introduction

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

Prototype

@Nullable
public static Object getField(Field field, @Nullable Object target) 

Source Link

Document

Get the field represented by the supplied Field field object on the specified Object target object .

Usage

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

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

@SuppressWarnings("unchecked")
@Test/*from www  .j a va 2  s.c o  m*/
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.querybyexample.jpa.JpaUtil.java

public static <T> Object getValue(T example, Attribute<? super T, ?> attr) {
    try {/*from   w w w.j  a  v a 2  s .c om*/
        if (attr.getJavaMember() instanceof Method) {
            return ReflectionUtils.invokeMethod((Method) attr.getJavaMember(), example);
        } else {
            return ReflectionUtils.getField((Field) attr.getJavaMember(), example);
        }
    } catch (Exception e) {
        throw propagate(e);
    }
}

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:net.sf.gazpachoquest.qbe.ByExampleSpecification.java

public <T extends Persistable> Specification<T> byExampleOnEntity(final T example, final SearchParameters sp) {
    Validate.notNull(example, "example must not be null");

    return new Specification<T>() {

        @Override//from  w ww.  j  a v a  2  s  .  c o m
        public Predicate toPredicate(final Root<T> rootPath, final CriteriaQuery<?> query,
                final CriteriaBuilder builder) {
            Class<T> type = rootPath.getModel().getBindableJavaType();

            ManagedType<T> mt = em.getMetamodel().entity(type);

            List<Predicate> predicates = new ArrayList<Predicate>();
            predicates.addAll(byExample(mt, rootPath, example, sp, builder));
            predicates.addAll(byExampleOnXToOne(mt, rootPath, example, sp, builder));
            // 1 level deep only
            predicates.addAll(byExampleOnManyToMany(mt, rootPath, example, sp, builder));
            // order by
            query.orderBy(JpaUtil.buildJpaOrders(sp.getOrders(), rootPath, builder));
            return JpaUtil.andPredicate(builder, predicates);
        }

        //https://github.com/jaxio/generated-projects/tree/master/jsf2-spring-conversation/src/main/generated-java/com/jaxio/appli/repository/support

        public <T extends Persistable> List<Predicate> byExample(final ManagedType<T> mt, final Path<T> mtPath,
                final T mtValue, final SearchParameters sp, final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
                if (attr.getPersistentAttributeType() == MANY_TO_ONE
                        || attr.getPersistentAttributeType() == ONE_TO_ONE
                        || attr.getPersistentAttributeType() == EMBEDDED
                        || attr.getJavaType().isAssignableFrom(Map.class)) {
                    continue;
                }
                Object attrValue = getValue(mtValue, attr);

                if (attrValue != null) {
                    if (attr.getJavaType() == String.class) {
                        if (isNotEmpty((String) attrValue)) {
                            SingularAttribute<? super T, String> stringAttribute = mt
                                    .getSingularAttribute(attr.getName(), String.class);
                            predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute), attrValue, sp,
                                    builder));
                        }
                    } else {
                        SingularAttribute<? super T, ?> attribute = mt.getSingularAttribute(attr.getName(),
                                attr.getJavaType());
                        // apply equal
                        predicates.add(builder.equal(mtPath.get(attribute), attrValue));
                    }
                }
            }
            return predicates;
        }

        /**
         * Construct a join predicate on collection (eg many to many, List)
         */
        public <T extends Persistable> List<Predicate> byExampleOnManyToMany(final ManagedType<T> mt,
                final Root<T> mtPath, final T mtValue, final SearchParameters sp,
                final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (PluralAttribute<T, ?, ?> pa : mt.getDeclaredPluralAttributes()) {
                if (pa.getCollectionType() == PluralAttribute.CollectionType.LIST) {
                    List<?> value = (List<?>) getValue(mtValue, mt.getAttribute(pa.getName()));

                    if (value != null && !value.isEmpty()) {
                        ListJoin<T, ?> join = mtPath.join(mt.getDeclaredList(pa.getName()));
                        predicates.add(join.in(value));
                    }
                }
                if (pa.getCollectionType() == PluralAttribute.CollectionType.SET) {
                    Set<?> value = (Set<?>) getValue(mtValue, mt.getAttribute(pa.getName()));

                    if (value != null && !value.isEmpty()) {
                        SetJoin<T, ?> join = mtPath.join(mt.getDeclaredSet(pa.getName()));
                        predicates.add(join.in(value));
                    }
                }
            }
            return predicates;
        }

        /**
         * Invoke byExample method for each not null x-to-one association
         * when their pk is not set. This allows you
         * to search entities based on an associated entity's properties
         * value.
         */
        @SuppressWarnings("unchecked")
        public <T extends Persistable, M2O extends Persistable> List<Predicate> byExampleOnXToOne(
                final ManagedType<T> mt, final Root<T> mtPath, final T mtValue, final SearchParameters sp,
                final CriteriaBuilder builder) {
            List<Predicate> predicates = new ArrayList<Predicate>();
            for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
                if (attr.getPersistentAttributeType() == MANY_TO_ONE
                        || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
                    M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));

                    if (m2oValue != null) {
                        Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                        ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                        Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                        predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                    }
                }
            }
            return predicates;
        }

        private <T> Object getValue(final T example, final Attribute<? super T, ?> attr) {
            Object value = null;
            try {
                if (attr.getJavaMember() instanceof Method) {
                    value = ((Method) attr.getJavaMember()).invoke(example, new Object[0]);
                } else if (attr.getJavaMember() instanceof Field) {
                    value = ReflectionUtils.getField((Field) attr.getJavaMember(), example);
                }

                if (value instanceof ValueHolderInterface) {
                    value = ((ValueHolderInterface) value).getValue();
                }

            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            return value;
        }

    };

}

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

@Test
public void testImportWordList_LeftoversFromBatch() {
    ThreadPoolTaskExecutor taskExecutorSpy = spy(new ThreadPoolTaskExecutor());
    taskExecutorSpy.setCorePoolSize(4);/*w ww. j a  v a  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: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);//from w w w.  ja v a2s.co m

    assertSame(compareToKnownSolution, compareToKnownSolutionFromObject);
}

From source file:com.javaetmoi.core.spring.vfs.Vfs2Utils.java

protected static Object doGetVisitorAttribute() {
    return ReflectionUtils.getField(VISITOR_ATTRIBUTES_FIELD_RECURSE, null);
}

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

@SuppressWarnings("unchecked")
@Test//w w w .j  av  a 2s. co  m
public void testCrossover_SmallPopulation() {
    ConcurrentMultigenerationalGeneticAlgorithm concurrentMultigenerationalGeneticAlgorithm = new ConcurrentMultigenerationalGeneticAlgorithm();

    Population population = new Population();

    Chromosome chromosome = new MockKeylessChromosome();
    population.addIndividual(chromosome);
    concurrentMultigenerationalGeneticAlgorithm.setPopulation(population);

    CrossoverAlgorithm crossoverAlgorithmMock = mock(CrossoverAlgorithm.class);

    Field crossoverAlgorithmField = ReflectionUtils.findField(ConcurrentMultigenerationalGeneticAlgorithm.class,
            "crossoverAlgorithm");
    ReflectionUtils.makeAccessible(crossoverAlgorithmField);
    ReflectionUtils.setField(crossoverAlgorithmField, concurrentMultigenerationalGeneticAlgorithm,
            crossoverAlgorithmMock);

    Field ineligibleForReproductionField = ReflectionUtils.findField(Population.class,
            "ineligibleForReproduction");
    ReflectionUtils.makeAccessible(ineligibleForReproductionField);
    List<Chromosome> ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(0, ineligibleForReproductionFromObject.size());

    int childrenProduced = concurrentMultigenerationalGeneticAlgorithm.crossover(10);

    ineligibleForReproductionFromObject = (List<Chromosome>) ReflectionUtils
            .getField(ineligibleForReproductionField, population);

    assertEquals(1, population.size());

    assertEquals(0, ineligibleForReproductionFromObject.size());

    assertEquals(0, childrenProduced);

    verifyZeroInteractions(crossoverAlgorithmMock);
}