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.algorithms.mutation.LiberalMutationAlgorithmTest.java

@Test
public void testSetGeneDao() {
    GeneDao geneDaoToSet = mock(GeneDao.class);

    LiberalMutationAlgorithm liberalMutationAlgorithm = new LiberalMutationAlgorithm();
    liberalMutationAlgorithm.setGeneDao(geneDaoToSet);

    Field geneDaoField = ReflectionUtils.findField(LiberalMutationAlgorithm.class, "geneDao");
    ReflectionUtils.makeAccessible(geneDaoField);
    GeneDao geneDaoFromObject = (GeneDao) ReflectionUtils.getField(geneDaoField, liberalMutationAlgorithm);

    assertSame(geneDaoToSet, geneDaoFromObject);
}

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

@Test
public void testSetConcurrencyBatchSize() {
    int concurrencyBatchSizeToSet = 250;
    WordListImporterImpl wordListImporterImpl = new WordListImporterImpl();
    wordListImporterImpl.setConcurrencyBatchSize(concurrencyBatchSizeToSet);

    Field concurrencyBatchSizeField = ReflectionUtils.findField(WordListImporterImpl.class,
            "concurrencyBatchSize");
    ReflectionUtils.makeAccessible(concurrencyBatchSizeField);
    int concurrencyBatchSizeFromObject = (int) ReflectionUtils.getField(concurrencyBatchSizeField,
            wordListImporterImpl);/*from  ww  w.j a  v a 2 s .  c om*/

    assertEquals(concurrencyBatchSizeToSet, concurrencyBatchSizeFromObject);
}

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

@Test
public void testSetGeneDao() {
    VariableLengthGeneDao geneDaoToSet = mock(VariableLengthGeneDao.class);

    GroupMutationAlgorithm groupMutationAlgorithm = new GroupMutationAlgorithm();
    groupMutationAlgorithm.setGeneDao(geneDaoToSet);

    Field geneDaoField = ReflectionUtils.findField(GroupMutationAlgorithm.class, "geneDao");
    ReflectionUtils.makeAccessible(geneDaoField);
    GeneDao geneDaoFromObject = (GeneDao) ReflectionUtils.getField(geneDaoField, groupMutationAlgorithm);

    assertSame(geneDaoToSet, geneDaoFromObject);
}

From source file:com.agileapes.couteau.context.spring.event.impl.AbstractMappedEventsTranslationScheme.java

@Override
public ApplicationEvent translate(Event originalEvent) throws EventTranslationException {
    final Class<? extends ApplicationEvent> eventClass;
    try {//from   w ww . j av  a  2  s .  c o m
        eventClass = getTargetEvent(originalEvent.getClass());
    } catch (ClassNotFoundException e) {
        throw new EventTranslationException("Failed to locate target class for event", e);
    }
    final ApplicationEvent applicationEvent;
    try {
        applicationEvent = eventClass.getConstructor(Object.class).newInstance(originalEvent.getSource());
    } catch (Exception e) {
        throw new EventTranslationException(
                "Failed to instantiate event from " + eventClass.getCanonicalName());
    }
    for (Method method : originalEvent.getClass().getMethods()) {
        if (!GenericTranslationScheme.isGetter(method)) {
            continue;
        }
        final String fieldName = StringUtils
                .uncapitalize(method.getName().substring(method.getName().startsWith("get") ? 3 : 2));
        final Field field = ReflectionUtils.findField(eventClass, fieldName);
        if (field == null || !field.getType().isAssignableFrom(method.getReturnType())) {
            continue;
        }
        field.setAccessible(true);
        try {
            field.set(applicationEvent, method.invoke(originalEvent));
        } catch (Exception e) {
            throw new EventTranslationException("Failed to set property: " + fieldName, e);
        }
    }
    return applicationEvent;
}

From source file:com.mariadb.embedded.MariadbServerTests.java

/**
 * Get {@link DBConfiguration} in {@link MariadbServer}.
 * //w  w w. j  a  va  2  s  .c  o m
 * @param server {@link MariadbServer}
 * @return {@link DBConfiguration}
 */
private DBConfiguration getConfiguration(MariadbServer server) {

    Field field = ReflectionUtils.findField(MariadbServer.class, "config");
    ReflectionUtils.makeAccessible(field);

    return (DBConfiguration) ReflectionUtils.getField(field, server);
}

From source file:py.una.pol.karaku.test.test.dao.SearchHelperTest.java

@Test
public void testGetField() throws NoSuchFieldException, SecurityException {

    assertEquals(ReflectionUtils.findField(TestEntity.class, "costo"),
            SearchHelper.getFieldInfo(TestEntity.class, "costo").getField());

    assertEquals(ReflectionUtils.findField(TestChild.class, "fecha"),
            SearchHelper.getFieldInfo(TestEntity.class, "testChild.fecha").getField());

    assertEquals(ReflectionUtils.findField(TestGrandChild.class, "fecha"),
            SearchHelper.getFieldInfo(TestEntity.class, "testChild.grandChilds.fecha").getField());

}

From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Read from exclude annotations to further 
 * populate exclude paths already parsed from XML.
 *//*from  w w w.j a va2 s.co  m*/
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initExcludePaths() {
    for (ValidationEntity entity : validationEntityMap.values()) {
        // no paths to check on an interface.
        if (entity.getValidationClass().isInterface()) {
            continue;
        }
        BeanWrapper entityWrapper = new BeanWrapperImpl(entity.getValidationClass());
        for (PropertyDescriptor descriptor : entityWrapper.getPropertyDescriptors()) {
            if (!entityWrapper.isReadableProperty(descriptor.getName())
                    || !entityWrapper.isWritableProperty(descriptor.getName())) {
                continue;
            }
            for (Class excludeAnnotation : excludeAnnotations) {
                try {
                    if (ReflectionUtils.findField(entity.getValidationClass(), descriptor.getName())
                            .getAnnotation(excludeAnnotation) != null) {
                        entity.getExcludedPaths().add(descriptor.getName());
                    }
                } catch (SecurityException se) {
                    throw new IllegalStateException("Unexpected error while checking for excluded properties",
                            se);
                }
            }
        }
    }
}

From source file:org.synyx.hades.dao.query.QueryMethod.java

/**
 * Returns whether the given field is valid field name and thus a persistent
 * field to the underlying domain class.
 * /*w ww.  j a v  a  2  s  . c  o  m*/
 * @param fieldName
 * @return
 */
boolean isValidField(String fieldName) {

    Class<?> returnType = ClassUtils.getReturnedDomainClass(method);

    if (null != ReflectionUtils.findMethod(returnType, "get" + fieldName)) {
        return true;
    }

    return null != ReflectionUtils.findField(returnType, StringUtils.uncapitalize(fieldName));
}

From source file:org.openmrs.module.webservices.rest.web.DelegatingCrudResourceTest.java

/**
 * This test looks at all subclasses of DelegatingCrudResource, and test all {@link RepHandler}
 * methods to make sure they are all capable of running without exceptions. It also checks that
 *//*from w  w w . j  ava 2  s.  com*/
@SuppressWarnings("rawtypes")
@Test
@Ignore
public void testAllReprsentationDescriptions() throws Exception {
    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true);
    //only match subclasses of BaseDelegatingResource
    provider.addIncludeFilter(new AssignableTypeFilter(BaseDelegatingResource.class));

    // scan in org.openmrs.module.webservices.rest.web.resource package 
    Set<BeanDefinition> components = provider
            .findCandidateComponents("org.openmrs.module.webservices.rest.web.resource");
    if (CollectionUtils.isEmpty(components))
        Assert.fail("Faile to load any resource classes");

    for (BeanDefinition component : components) {
        Class resourceClass = Class.forName(component.getBeanClassName());
        for (Method method : ReflectionUtils.getAllDeclaredMethods(resourceClass)) {
            ParameterizedType parameterizedType = (ParameterizedType) resourceClass.getGenericSuperclass();
            Class openmrsClass = (Class) parameterizedType.getActualTypeArguments()[0];
            //User Resource is special in that the Actual parameterized Type isn't a standard domain object, so we also
            //need to look up fields and methods from the org.openmrs.User class 
            boolean isUserResource = resourceClass.equals(UserResource1_8.class);
            List<Object> refDescriptions = new ArrayList<Object>();

            if (method.getName().equals("getRepresentationDescription")
                    && method.getDeclaringClass().equals(resourceClass)) {
                //get all the rep definitions for all representations
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.REF }));
                refDescriptions.add(
                        method.invoke(resourceClass.newInstance(), new Object[] { Representation.DEFAULT }));
                refDescriptions
                        .add(method.invoke(resourceClass.newInstance(), new Object[] { Representation.FULL }));
            }

            for (Object value : refDescriptions) {
                if (value != null) {
                    DelegatingResourceDescription des = (DelegatingResourceDescription) value;
                    for (String key : des.getProperties().keySet()) {
                        if (!key.equals("uri") && !key.equals("display") && !key.equals("auditInfo")) {
                            boolean hasFieldOrPropertySetter = (ReflectionUtils.findField(openmrsClass,
                                    key) != null);
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findField(User.class,
                                            key) != null);
                            }
                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = hasSetterMethod(key, resourceClass);

                            //TODO replace this hacky way that we are using to check if there is a get method for a 
                            //collection that has no actual getter e.g activeIdentifers and activeAttributes for Patient
                            if (!hasFieldOrPropertySetter) {
                                hasFieldOrPropertySetter = (ReflectionUtils.findMethod(openmrsClass,
                                        "get" + StringUtils.capitalize(key)) != null);
                                if (!hasFieldOrPropertySetter && isUserResource)
                                    hasFieldOrPropertySetter = (ReflectionUtils.findMethod(User.class,
                                            "get" + StringUtils.capitalize(key)) != null);
                            }

                            if (!hasFieldOrPropertySetter)
                                hasFieldOrPropertySetter = isallowedMissingProperty(resourceClass, key);

                            Assert.assertTrue(
                                    "No property found for '" + key + "' for " + openmrsClass
                                            + " nor setter method on resource " + resourceClass,
                                    hasFieldOrPropertySetter);
                        }
                    }
                }
            }
        }
    }
}

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

@Test
public void testSetSolutionDao() {
    SolutionDao solutionDaoToSet = mock(SolutionDao.class);
    GeneticCipherSolutionService geneticCipherSolutionService = new GeneticCipherSolutionService();
    geneticCipherSolutionService.setSolutionDao(solutionDaoToSet);

    Field solutionDaoField = ReflectionUtils.findField(GeneticCipherSolutionService.class, "solutionDao");
    ReflectionUtils.makeAccessible(solutionDaoField);
    SolutionDao solutionDaoFromObject = (SolutionDao) ReflectionUtils.getField(solutionDaoField,
            geneticCipherSolutionService);

    assertSame(solutionDaoToSet, solutionDaoFromObject);
}