List of usage examples for org.springframework.beans BeanUtils instantiateClass
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException
From source file:edu.pitt.dbmi.ccd.anno.annotation.data.AnnotationDataResourceAssembler.java
/** * Instantiate AnnotationDataResource with non-default constructor * * @param annotation entity//from w w w . jav a2 s.c om * @return resource */ @Override protected AnnotationDataResource instantiateResource(AnnotationData annotation) throws IllegalArgumentException { Assert.notNull(annotation); try { return BeanUtils.instantiateClass(AnnotationDataResource.class.getConstructor(AnnotationData.class), annotation); } catch (NoSuchMethodException ex) { ex.printStackTrace(); return new AnnotationDataResource(); } }
From source file:de.itsvs.cwtrpc.security.SimpleRpcAuthenticationFailureHandler.java
protected Exception createRemoteException(HttpServletRequest request, AuthenticationException exception, Class<? extends Exception> remoteExceptionClass) { final Constructor<? extends Exception> constructor; Exception remoteException;/*from w w w .j av a 2s. co m*/ if (isIncludeExceptionMessage()) { constructor = getMessageConstructor(remoteExceptionClass); } else { constructor = null; } try { if (constructor != null) { if (log.isDebugEnabled()) { log.debug("Creating remote exception " + remoteExceptionClass.getName() + " with message of original exception"); } remoteException = BeanUtils.instantiateClass(constructor, new Object[] { exception.getMessage() }); } else { remoteException = BeanUtils.instantiateClass(remoteExceptionClass); } } catch (BeanInstantiationException e) { log.error("Could not create remote exception: " + remoteExceptionClass.getName(), e); remoteException = null; } return remoteException; }
From source file:edu.pitt.dbmi.ccd.anno.annotation.AnnotationResourceAssembler.java
/** * Instantiate AnnotationResource with non-default constructor * * @param annotation entity//from w w w . j a va 2 s . c o m * @return resource */ @Override protected AnnotationResource instantiateResource(Annotation annotation) throws IllegalArgumentException { Assert.notNull(annotation); try { return BeanUtils.instantiateClass(AnnotationResource.class.getConstructor(Annotation.class), annotation); } catch (NoSuchMethodException ex) { ex.printStackTrace(); return new AnnotationResource(); } }
From source file:org.spring.guice.annotation.GuiceModuleRegistrar.java
private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) { List<TypeFilter> typeFilters = new ArrayList<TypeFilter>(); FilterType filterType = filterAttributes.getEnum("type"); for (Class<?> filterClass : filterAttributes.getClassArray("value")) { switch (filterType) { case ANNOTATION: Assert.isAssignable(Annotation.class, filterClass, "An error occured when processing a @ComponentScan " + "ANNOTATION type filter: "); @SuppressWarnings("unchecked") Class<Annotation> annoClass = (Class<Annotation>) filterClass; typeFilters.add(new AnnotationTypeFilter(annoClass)); break; case ASSIGNABLE_TYPE: typeFilters.add(new AssignableTypeFilter(filterClass)); break; case CUSTOM: Assert.isAssignable(TypeFilter.class, filterClass, "An error occured when processing a @ComponentScan " + "CUSTOM type filter: "); typeFilters.add(BeanUtils.instantiateClass(filterClass, TypeFilter.class)); break; default:/*ww w . j ava2 s . co m*/ throw new IllegalArgumentException("Unknown filter type " + filterType); } } for (String expression : getPatterns(filterAttributes)) { String rawName = filterType.toString(); if ("REGEX".equals(rawName)) { typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression))); } else if ("ASPECTJ".equals(rawName)) { typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader())); } else { throw new IllegalArgumentException("Unknown filter type " + filterType); } } return typeFilters; }
From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), for the specified property. * /*from w w w. j a v a2 s . c om*/ * @param propertyName * name of the property * @param oldValue * the previous value, if available (may be <code>null</code>) * @param newValue * the proposed new value * @param requiredType * the type we must convert to (or <code>null</code> if not known, for example in case of a collection * element) * @param typeDescriptor * the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException * if type conversion failed */ @SuppressWarnings("unchecked") public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException { Object convertedValue = newValue; // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException firstAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); TypeDescriptor targetTypeDesc = typeDescriptor; if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) { try { return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc); } catch (ConversionFailedException ex) { // fallback to default conversion logic below firstAttemptEx = ex; } } } // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor(); if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor strCtor = requiredType.getConstructor(String.class); return (T) BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (firstAttemptEx != null) { throw firstAttemptEx; } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type [") .append(ClassUtils.getDescriptiveType(convertedValue)).append("]"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (firstAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && !Object.class.equals(requiredType)) { throw firstAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", firstAttemptEx); } return (T) convertedValue; }
From source file:org.grails.orm.hibernate.SessionFactoryProxy.java
@SuppressWarnings("unchecked") protected CurrentSessionContext createCurrentSessionContext() { Class sessionContextClass = currentSessionContextClass; if (sessionContextClass == null) { sessionContextClass = GrailsSessionContext.class; }/*from ww w . j av a 2 s. c om*/ try { Constructor<CurrentSessionContext> constructor = sessionContextClass .getConstructor(SessionFactoryImplementor.class); return BeanUtils.instantiateClass(constructor, this); } catch (NoSuchMethodException e) { return new GrailsSessionContext(this); } }
From source file:grails.util.GrailsMetaClassUtils.java
/** * Copies the ExpandoMetaClass dynamic methods and properties from one Class to another. * * @param fromClass The source class/*from www . ja va 2s. com*/ * @param toClass The destination class * @param removeSource Whether to remove the source class after completion. True if yes */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void copyExpandoMetaClass(Class<?> fromClass, Class<?> toClass, boolean removeSource) { MetaClassRegistry registry = getRegistry(); MetaClass oldMetaClass = registry.getMetaClass(fromClass); AdaptingMetaClass adapter = null; ExpandoMetaClass emc; if (oldMetaClass instanceof AdaptingMetaClass) { adapter = ((AdaptingMetaClass) oldMetaClass); emc = (ExpandoMetaClass) adapter.getAdaptee(); if (LOG.isDebugEnabled()) { LOG.debug("Obtained adapted MetaClass [" + emc + "] from AdapterMetaClass instance [" + adapter + "]"); } if (removeSource) { registry.removeMetaClass(fromClass); } } else { emc = (ExpandoMetaClass) oldMetaClass; if (LOG.isDebugEnabled()) { LOG.debug("No adapter MetaClass found, using original [" + emc + "]"); } } ExpandoMetaClass replacement = new ExpandoMetaClass(toClass, true, true); for (Object obj : emc.getExpandoMethods()) { if (obj instanceof ClosureInvokingMethod) { ClosureInvokingMethod cim = (ClosureInvokingMethod) obj; Closure callable = cim.getClosure(); if (!cim.isStatic()) { replacement.setProperty(cim.getName(), callable); } else { ((GroovyObject) replacement.getProperty(ExpandoMetaClass.STATIC_QUALIFIER)) .setProperty(cim.getName(), callable); } } } for (Object o : emc.getExpandoProperties()) { if (o instanceof ThreadManagedMetaBeanProperty) { ThreadManagedMetaBeanProperty mbp = (ThreadManagedMetaBeanProperty) o; replacement.setProperty(mbp.getName(), mbp.getInitialValue()); } } replacement.initialize(); if (adapter == null) { if (LOG.isDebugEnabled()) { LOG.debug("Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "]"); } registry.setMetaClass(toClass, replacement); } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding MetaClass for class [" + toClass + "] MetaClass [" + replacement + "] with adapter [" + adapter + "]"); } try { Constructor c = adapter.getClass().getConstructor(new Class[] { MetaClass.class }); MetaClass newAdapter = (MetaClass) BeanUtils.instantiateClass(c, new Object[] { replacement }); registry.setMetaClass(toClass, newAdapter); } catch (NoSuchMethodException e) { if (LOG.isDebugEnabled()) { LOG.debug( "Exception thrown constructing new MetaClass adapter when reloading: " + e.getMessage(), e); } } } }
From source file:org.grails.web.errors.GrailsExceptionResolver.java
protected void createStackFilterer() { try {//from ww w . j av a 2 s .c o m Class filtererClass = grailsApplication.getConfig().getProperty( Settings.SETTING_LOGGING_STACKTRACE_FILTER_CLASS, Class.class, DefaultStackTraceFilterer.class); stackFilterer = BeanUtils.instantiateClass(filtererClass, StackTraceFilterer.class); } catch (Throwable t) { logger.error("Problem instantiating StackTracePrinter class, using default: " + t.getMessage()); stackFilterer = new DefaultStackTraceFilterer(); } }
From source file:org.springframework.beans.factory.support.SimpleInstantiationStrategy.java
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner, Constructor ctor, Object[] args) { if (beanDefinition.getMethodOverrides().isEmpty()) { return BeanUtils.instantiateClass(ctor, args); } else {//from w ww. j a v a2 s. com return instantiateWithMethodInjection(beanDefinition, beanName, owner, ctor, args); } }
From source file:org.springframework.beans.TypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property./* w w w . j av a2 s . c o m*/ * @param propertyName name of the property * @param oldValue the previous value, if available (may be {@code null}) * @param newValue the proposed new value * @param requiredType the type we must convert to * (or {@code null} if not known, for example in case of a collection element) * @param typeDescriptor the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException if type conversion failed */ @SuppressWarnings("unchecked") @Nullable public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor) throws IllegalArgumentException { // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException conversionAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { try { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } catch (ConversionFailedException ex) { // fallback to default conversion logic below conversionAttemptEx = ex; } } } Object convertedValue = newValue; // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor(); if (elementTypeDesc != null) { Class<?> elementType = elementTypeDesc.getType(); if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (Object.class == requiredType) { return (T) convertedValue; } else if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor<T> strCtor = requiredType.getConstructor(String.class); return BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) { convertedValue = NumberUtils.convertNumberToTargetClass((Number) convertedValue, (Class<Number>) requiredType); standardConversion = true; } } else { // convertedValue == null if (requiredType == Optional.class) { convertedValue = Optional.empty(); } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (conversionAttemptEx != null) { // Original exception from former ConversionService call above... throw conversionAttemptEx; } else if (conversionService != null && typeDescriptor != null) { // ConversionService not tried before, probably custom editor found // but editor couldn't produce the required type... TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type '").append(ClassUtils.getDescriptiveType(newValue)); msg.append("' to required type '").append(ClassUtils.getQualifiedName(requiredType)).append("'"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type '") .append(ClassUtils.getDescriptiveType(convertedValue)).append("'"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (conversionAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) { throw conversionAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", conversionAttemptEx); } return (T) convertedValue; }