Example usage for org.springframework.beans BeanUtils instantiateClass

List of usage examples for org.springframework.beans BeanUtils instantiateClass

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils instantiateClass.

Prototype

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Instantiate a class using its 'primary' constructor (for Kotlin classes, potentially having default arguments declared) or its default constructor (for regular Java classes, expecting a standard no-arg setup).

Usage

From source file:org.mybatis.spring.annotation.MapperScannerRegistrar.java

/**
 * {@inheritDoc}/*  w  w  w  .j a  v  a  2s.c o m*/
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
        BeanDefinitionRegistry registry) {

    AnnotationAttributes annoAttrs = AnnotationAttributes
            .fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
    ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);

    // this check is needed in Spring 3.1
    if (resourceLoader != null) {
        scanner.setResourceLoader(resourceLoader);
    }

    Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
    if (!Annotation.class.equals(annotationClass)) {
        scanner.setAnnotationClass(annotationClass);
    }

    Class<?> markerInterface = annoAttrs.getClass("markerInterface");
    if (!Class.class.equals(markerInterface)) {
        scanner.setMarkerInterface(markerInterface);
    }

    Class<? extends BeanNameGenerator> generatorClass = annoAttrs.getClass("nameGenerator");
    if (!BeanNameGenerator.class.equals(generatorClass)) {
        scanner.setBeanNameGenerator(BeanUtils.instantiateClass(generatorClass));
    }

    Class<? extends MapperFactoryBean> mapperFactoryBeanClass = annoAttrs.getClass("factoryBean");
    if (!MapperFactoryBean.class.equals(mapperFactoryBeanClass)) {
        scanner.setMapperFactoryBean(BeanUtils.instantiateClass(mapperFactoryBeanClass));
    }

    scanner.setSqlSessionTemplateBeanName(annoAttrs.getString("sqlSessionTemplateRef"));
    scanner.setSqlSessionFactoryBeanName(annoAttrs.getString("sqlSessionFactoryRef"));

    List<String> basePackages = new ArrayList<String>();
    for (String pkg : annoAttrs.getStringArray("value")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    for (String pkg : annoAttrs.getStringArray("basePackages")) {
        if (StringUtils.hasText(pkg)) {
            basePackages.add(pkg);
        }
    }
    for (Class<?> clazz : annoAttrs.getClassArray("basePackageClasses")) {
        basePackages.add(ClassUtils.getPackageName(clazz));
    }
    scanner.registerFilters();
    scanner.doScan(StringUtils.toStringArray(basePackages));
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Returns the value of the specified property and type from an instance of the specified Griffon class
 *
 * @param clazz The name of the class which contains the property
 * @param propertyName The property name
 * @param propertyType The property type
 *
 * @return The value of the property or null if none exists
 *///from w w  w  .  ja  va2  s .  c  o  m
public static Object getPropertyValueOfNewInstance(Class clazz, String propertyName, Class propertyType) {
    // validate
    if (clazz == null || StringUtils.isBlank(propertyName))
        return null;

    Object instance = null;
    try {
        instance = BeanUtils.instantiateClass(clazz);
    } catch (BeanInstantiationException e) {
        return null;
    }

    return getPropertyOrStaticPropertyOrFieldValue(instance, propertyName);
}

From source file:org.motechproject.server.osgi.OsgiFrameworkServiceTest.java

private WebApplicationContext getWebApplicationContext() {
    GenericWebApplicationContext wac = BeanUtils.instantiateClass(GenericWebApplicationContext.class);
    wac.setParent(applicationContext);//from w  w  w.  j a v  a2 s.  com
    wac.setServletContext(new MockServletContext());
    return wac;
}

From source file:org.opentides.web.processor.FormBindMethodProcessor.java

/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default. The model attribute is then populated with request values 
 * via data binding and validated. If no validation error, the model
 * is retrieved from database and merged with the submitted form.
 *   //from   w w  w  .  ja  v  a  2 s  .co  m
 * @throws BindException if data binding and validation result in an error
 * @throws Exception if WebDataBinder initialization fails.
 */
@SuppressWarnings("unchecked")
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest nativeRequest, WebDataBinderFactory binderFactory) throws Exception {

    FormBind annot = parameter.getParameterAnnotation(FormBind.class);
    Class<?> clazz = parameter.getDeclaringClass();
    String name = getName(annot, parameter);
    HttpServletRequest request = (HttpServletRequest) nativeRequest.getNativeRequest();

    Method addForm = CacheUtil.getNewFormBindMethod(clazz);
    Object controller = beanFactory.getBean(parameter.getContainingClass());
    Object target = (addForm != null) ? addForm.invoke(controller, request)
            : BeanUtils.instantiateClass(parameter.getParameterType());
    MutablePropertyValues mpvs = new MutablePropertyValues(nativeRequest.getParameterMap());
    WebDataBinder binder = binderFactory.createBinder(nativeRequest, target, name);
    if (binder.getTarget() != null) {
        binder.bind(mpvs);
        if (binder.getValidator() != null)
            binder.validate();
        if (binder.getBindingResult().hasErrors()) {
            throw new BindException(binder.getBindingResult());
        }
        String method = request.getMethod().toLowerCase();

        // id should be the last segment of the uri
        String uri = request.getRequestURI();
        String sid = uri.substring(uri.lastIndexOf("/") + 1);
        Long id = StringUtil.convertToLong(sid, 0);

        // if target extends BaseEntity and for update, link target to database record
        if (("put".equals(method) || "post".equals(method)) && id > 0
                && BaseEntity.class.isAssignableFrom(parameter.getParameterType())) {
            // now retrieve record from database for updating
            Method updateForm = CacheUtil.getUpdateFormBindMethod(clazz);

            BaseEntity record = null;
            if (updateForm == null) {
                // no annotation, invoke from service
                Method getService = controller.getClass().getMethod("getService");
                if (getService == null) {
                    String message = "Cannot find method with @FormBind with update mode. "
                            + "Also, unable to find service associated to controller."
                            + "Please specify one that retrieves record from database.";
                    throw new InvalidImplementationException(message);
                }
                BaseCrudService<? extends BaseEntity> service = (BaseCrudService<? extends BaseEntity>) getService
                        .invoke(controller);
                record = (BaseEntity) service.load(sid);
            } else {
                // with annotation, invoke annotation
                record = (BaseEntity) updateForm.invoke(controller, sid, request);
            }

            if (record != null) {
                WebDataBinder updateBinder = binderFactory.createBinder(nativeRequest, record, name);
                updateBinder.bind(mpvs);
                mavContainer.addAllAttributes(updateBinder.getBindingResult().getModel());
                return updateBinder.getTarget();
            } else {
                String message = "Unable to find " + parameter.getParameterType().getSimpleName() + " with id="
                        + sid + " for update.";
                throw new DataAccessException(message);
            }
        } else if ("post".equals(method)) {
            mavContainer.addAllAttributes(binder.getBindingResult().getModel());
            return binder.getTarget();
        } else {
            throw new InvalidImplementationException(
                    "@FormBind argument annotation can only be used on POST or PUT methods.");
        }
    }
    mavContainer.addAllAttributes(binder.getBindingResult().getModel());
    return binder.getTarget();
}

From source file:com.taobao.itest.core.TestContextManager.java

private TestListener[] retrieveTestListeners(Class<?> clazz) {
    Class<TestListeners> annotationType = TestListeners.class;
    @SuppressWarnings("rawtypes")
    List<Class> classesAnnotationDeclared = AnnotationUtil.findClassesAnnotationDeclaredWith(clazz,
            annotationType);/*from  w  ww  .  ja v  a  2 s.c o m*/
    List<Class<? extends TestListener>> classesList = new ArrayList<Class<? extends TestListener>>();
    for (Class<?> classAnnotationDeclared : classesAnnotationDeclared) {
        TestListeners testListeners = classAnnotationDeclared.getAnnotation(annotationType);
        Class<? extends TestListener>[] valueListenerClasses = testListeners.value();
        Class<? extends TestListener>[] listenerClasses = testListeners.listeners();
        if (!ArrayUtils.isEmpty(valueListenerClasses) && !ArrayUtils.isEmpty(listenerClasses)) {
            String msg = String.format(
                    "Test class [%s] has been configured with @TestListeners' 'value' [%s] and 'listeners' [%s] attributes. Use one or the other, but not both.",
                    classAnnotationDeclared, ArrayUtils.toString(valueListenerClasses),
                    ArrayUtils.toString(listenerClasses));
            throw new RuntimeException(msg);
        } else if (!ArrayUtils.isEmpty(valueListenerClasses)) {
            listenerClasses = valueListenerClasses;
        }

        if (listenerClasses != null) {
            classesList.addAll(0, Arrays.<Class<? extends TestListener>>asList(listenerClasses));
        }
        if (!testListeners.inheritListeners()) {
            break;
        }
    }

    List<TestListener> listeners = new ArrayList<TestListener>(classesList.size());
    for (Class<? extends TestListener> listenerClass : classesList) {
        listeners.add((TestListener) BeanUtils.instantiateClass(listenerClass));
    }
    return listeners.toArray(new TestListener[listeners.size()]);
}

From source file:org.springmodules.validation.bean.conf.loader.annotation.handler.hibernate.HibernatePropertyValidationAnnotationHandler.java

/**
 * Handles the given property level annotation and manipulates the given bean validation configuration accordingly.
 *
 * @param annotation The annotation to handle.
 * @param clazz The annotated class.//www.j a v  a  2s.c o m
 * @param descriptor The property descriptor of the annotated property.
 * @param configuration The bean validation configuration to manipulate.
 */
public void handleAnnotation(Annotation annotation, Class clazz, PropertyDescriptor descriptor,
        MutableBeanValidationConfiguration configuration) {

    if (annotation instanceof Valid) {
        configuration.addCascadeValidation(new CascadeValidation(descriptor.getName()));
        return;
    }

    Class annotationClass = annotation.annotationType();
    ValidatorClass validatorClassAnnotation = (ValidatorClass) annotationClass
            .getAnnotation(ValidatorClass.class);
    Class<? extends Validator> validatorClass = validatorClassAnnotation.value();
    Validator validator = (Validator) BeanUtils.instantiateClass(validatorClass);
    validator.initialize(annotation);
    Condition condition = Conditions.property(descriptor.getName(), new HibernateValidatorCondition(validator));
    String message;
    try {
        message = (String) annotationClass.getMethod("message").invoke(annotation);
    } catch (NoSuchMethodException nsme) {
        message = annotationClass.getSimpleName() + ".error";
    } catch (IllegalAccessException e) {
        message = annotationClass.getSimpleName() + ".error";
    } catch (InvocationTargetException e) {
        message = annotationClass.getSimpleName() + ".error";
    }

    configuration.addPropertyRule(descriptor.getName(),
            new DefaultValidationRule(condition, message, message, new Object[0]));

}

From source file:org.shept.persistence.provider.ScrollingListProviderFactory.java

public ScrollingListProvider getScrollingList(FilterDefinition filterProvider)
        throws UnsupportedFilterException {
    Class<?> clazz;//from   w w  w.j ava2s.  co  m
    // Hibernate support
    if (HibernateDaoSupportExtended.class.isAssignableFrom(getDao().getClass())) {
        if (filterProvider instanceof QueryDefinition) {
            clazz = HibernateQueryListProviderImpl.class;
        } else if (filterProvider instanceof HibernateCriteriaDefinition) {
            clazz = HibernateCriteriaListProviderImpl.class;
        } else if (filterProvider instanceof ExampleDefinition) {
            clazz = HibernateExampleListProviderImpl.class;
        } else if (filterProvider instanceof ReloadableAssociation) {
            clazz = HibernateAssociationProvider.class;
            ;
        } else {
            throw new UnsupportedFilterException("The filterProvider class: " + filterProvider.getClass()
                    + " is not supported for Hibernate access");
        }
    } else if ((HibernateDaoSupport.class.isAssignableFrom(getDao().getClass()))) {
        throw new UnsupportedDataProviderException(
                "For DataAccess via Hibernate the extended version of HibernateSupport is neccessary. "
                        + "Please use HibernateDaoSupportExtended instead of HibernateDaoSupport. "
                        + "If your dao object inherits from HibernateDaoSupport please inherit from HibernateDaoSupportExtended instead");
    }
    // support of other wrappers
    else {
        throw new UnsupportedDataProviderException("This version only supports Hibernate as the dao wrapper.");
    }
    ScrollingListProvider sp = (ScrollingListProvider) BeanUtils.instantiateClass(clazz);
    sp.setDao(dao);
    sp.setLoadSize(initialLoadSize);
    return sp;
}

From source file:io.github.resilience4j.circuitbreaker.configure.CircuitBreakerConfigurationProperties.java

protected void buildRecordFailurePredicate(BackendProperties properties, Builder builder) {
    builder.recordFailure(BeanUtils.instantiateClass(properties.getRecordFailurePredicate()));
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Returns the value of the specified property and type from an instance of the specified Griffon class
 *
 * @param clazz The name of the class which contains the property
 * @param propertyName The property name
 *
 * @return The value of the property or null if none exists
 *//*from   w  w  w  .j  a v a 2s . c o  m*/
public static Object getPropertyValueOfNewInstance(Class clazz, String propertyName) {
    // validate
    if (clazz == null || StringUtils.isBlank(propertyName))
        return null;

    Object instance = null;
    try {
        instance = BeanUtils.instantiateClass(clazz);
    } catch (BeanInstantiationException e) {
        return null;
    }

    return getPropertyOrStaticPropertyOrFieldValue(instance, propertyName);
}

From source file:ei.ne.ke.cassandra.cql3.CompoundEntitySpecification.java

/**
 * {@inheritDoc}
 */
@Override
public ID constructKey() {
    return BeanUtils.instantiateClass(keyClazz);
}