diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java index f1275daea40..95378f9e67a 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,12 @@ package org.springframework.aop.aspectj; +import java.lang.reflect.InvocationTargetException; + import org.springframework.aop.framework.AopConfigException; import org.springframework.core.Ordered; import org.springframework.util.Assert; +import org.springframework.util.ReflectionUtils; /** * Implementation of {@link AspectInstanceFactory} that creates a new instance @@ -52,13 +55,23 @@ public class SimpleAspectInstanceFactory implements AspectInstanceFactory { @Override public final Object getAspectInstance() { try { - return this.aspectClass.newInstance(); + return ReflectionUtils.accessibleConstructor(this.aspectClass).newInstance(); + } + catch (NoSuchMethodException ex) { + throw new AopConfigException( + "No default constructor on aspect class: " + this.aspectClass.getName(), ex); } catch (InstantiationException ex) { - throw new AopConfigException("Unable to instantiate aspect class [" + this.aspectClass.getName() + "]", ex); + throw new AopConfigException( + "Unable to instantiate aspect class: " + this.aspectClass.getName(), ex); } catch (IllegalAccessException ex) { - throw new AopConfigException("Cannot access element class [" + this.aspectClass.getName() + "]", ex); + throw new AopConfigException( + "Could not access aspect constructor: " + this.aspectClass.getName(), ex); + } + catch (InvocationTargetException ex) { + throw new AopConfigException( + "Failed to invoke aspect constructor: " + this.aspectClass.getName(), ex.getTargetException()); } } diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java index a485bcbc504..5f87a852dda 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java @@ -24,7 +24,7 @@ import org.aspectj.lang.reflect.PerClauseKind; import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.AspectJProxyUtils; -import org.springframework.aop.framework.AopConfigException; +import org.springframework.aop.aspectj.SimpleAspectInstanceFactory; import org.springframework.aop.framework.ProxyCreatorSupport; import org.springframework.aop.support.AopUtils; import org.springframework.core.annotation.AnnotationAwareOrderComparator; @@ -167,17 +167,9 @@ public class AspectJProxyFactory extends ProxyCreatorSupport { if (instance != null) { return instance; } - try { - instance = aspectClass.newInstance(); - aspectCache.put(aspectClass, instance); - return instance; - } - catch (InstantiationException ex) { - throw new AopConfigException("Unable to instantiate aspect class [" + aspectClass.getName() + "]", ex); - } - catch (IllegalAccessException ex) { - throw new AopConfigException("Cannot access aspect class [" + aspectClass.getName() + "]", ex); - } + instance = new SimpleAspectInstanceFactory(aspectClass).getAspectInstance(); + aspectCache.put(aspectClass, instance); + return instance; } } diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java b/spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java index 0da31db26b7..89e47fe2953 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.aop.framework; +import java.lang.reflect.Constructor; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -23,6 +25,7 @@ import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.Factory; import org.springframework.objenesis.SpringObjenesis; +import org.springframework.util.ReflectionUtils; /** * Objenesis-based extension of {@link CglibAopProxy} to create proxy instances @@ -68,9 +71,12 @@ class ObjenesisCglibAopProxy extends CglibAopProxy { if (proxyInstance == null) { // Regular instantiation via default constructor... try { + Constructor ctor = (this.constructorArgs != null ? + proxyClass.getDeclaredConstructor(this.constructorArgTypes) : + proxyClass.getDeclaredConstructor()); + ReflectionUtils.makeAccessible(ctor); proxyInstance = (this.constructorArgs != null ? - proxyClass.getConstructor(this.constructorArgTypes).newInstance(this.constructorArgs) : - proxyClass.newInstance()); + ctor.newInstance(this.constructorArgs) : ctor.newInstance()); } catch (Throwable ex) { throw new AopConfigException("Unable to instantiate proxy using Objenesis, " + diff --git a/spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java b/spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java index 5bbb37e6f6e..52353a52a84 100644 --- a/spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java +++ b/spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java @@ -24,6 +24,7 @@ import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.DynamicIntroductionAdvice; import org.springframework.aop.IntroductionInterceptor; import org.springframework.aop.ProxyMethodInvocation; +import org.springframework.util.ReflectionUtils; /** * Convenient implementation of the @@ -131,7 +132,7 @@ public class DelegatePerTargetObjectIntroductionInterceptor extends Introduction private Object createNewDelegate() { try { - return this.defaultImplType.newInstance(); + return ReflectionUtils.accessibleConstructor(this.defaultImplType).newInstance(); } catch (Throwable ex) { throw new IllegalArgumentException("Cannot create default implementation for '" + diff --git a/spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java b/spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java index 5067883c5e2..207705d10a2 100644 --- a/spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java @@ -18,7 +18,9 @@ package org.springframework.beans; import java.beans.PropertyChangeEvent; import java.lang.reflect.Array; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Modifier; import java.lang.reflect.UndeclaredThrowableException; import java.security.PrivilegedActionException; import java.util.ArrayList; @@ -890,14 +892,16 @@ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyA return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16); } else { - return BeanUtils.instantiate(type); + Constructor ctor = type.getDeclaredConstructor(); + if (Modifier.isPrivate(ctor.getModifiers())) { + throw new IllegalAccessException("Auto-growing not allowed with private constructor: " + ctor); + } + return BeanUtils.instantiateClass(ctor); } } - catch (Exception ex) { - // TODO: Root cause exception context is lost here; just exception message preserved. - // Should we throw another exception type that preserves context instead? + catch (Throwable ex) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name, - "Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path: " + ex); + "Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path", ex); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java b/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java index 2eb3eb91633..384b8a69351 100644 --- a/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java +++ b/spring-beans/src/main/java/org/springframework/beans/BeanUtils.java @@ -63,12 +63,14 @@ public abstract class BeanUtils { /** * Convenience method to instantiate a class using its no-arg constructor. - * As this method doesn't try to load classes by name, it should avoid - * class-loading issues. * @param clazz class to instantiate * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated + * @deprecated as of Spring 5.0, following the deprecation of + * {@link Class#newInstance()} in JDK 9 + * @see Class#newInstance() */ + @Deprecated public static T instantiate(Class clazz) throws BeanInstantiationException { Assert.notNull(clazz, "Class must not be null"); if (clazz.isInterface()) { @@ -87,13 +89,12 @@ public abstract class BeanUtils { /** * Instantiate a class using its no-arg constructor. - * As this method doesn't try to load classes by name, it should avoid - * class-loading issues. *

Note that this method tries to set the constructor accessible * if given a non-accessible (that is, non-public) constructor. * @param clazz class to instantiate * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated + * @see Constructor#newInstance */ public static T instantiateClass(Class clazz) throws BeanInstantiationException { Assert.notNull(clazz, "Class must not be null"); @@ -111,17 +112,15 @@ public abstract class BeanUtils { /** * Instantiate a class using its no-arg constructor and return the new instance * as the specified assignable type. - *

Useful in cases where - * the type of the class to instantiate (clazz) is not available, but the type - * desired (assignableTo) is known. - *

As this method doesn't try to load classes by name, it should avoid - * class-loading issues. - *

Note that this method tries to set the constructor accessible - * if given a non-accessible (that is, non-public) constructor. + *

Useful in cases where the type of the class to instantiate (clazz) is not + * available, but the type desired (assignableTo) is known. + *

Note that this method tries to set the constructor accessible if given a + * non-accessible (that is, non-public) constructor. * @param clazz class to instantiate * @param assignableTo type that clazz must be assignableTo * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated + * @see Constructor#newInstance */ @SuppressWarnings("unchecked") public static T instantiateClass(Class clazz, Class assignableTo) throws BeanInstantiationException { @@ -131,14 +130,13 @@ public abstract class BeanUtils { /** * Convenience method to instantiate a class using the given constructor. - * As this method doesn't try to load classes by name, it should avoid - * class-loading issues. - *

Note that this method tries to set the constructor accessible - * if given a non-accessible (that is, non-public) constructor. + *

Note that this method tries to set the constructor accessible if given a + * non-accessible (that is, non-public) constructor. * @param ctor the constructor to instantiate * @param args the constructor arguments to apply * @return the new instance * @throws BeanInstantiationException if the bean cannot be instantiated + * @see Constructor#newInstance */ public static T instantiateClass(Constructor ctor, Object... args) throws BeanInstantiationException { Assert.notNull(ctor, "Constructor must not be null"); diff --git a/spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java b/spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java index e01fafbfec6..e15885bc8ad 100644 --- a/spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java +++ b/spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ package org.springframework.beans; * spouse property of the target object has a null value. * * @author Rod Johnson + * @author Juergen Hoeller */ @SuppressWarnings("serial") public class NullValueInNestedPathException extends InvalidPropertyException { @@ -47,4 +48,16 @@ public class NullValueInNestedPathException extends InvalidPropertyException { super(beanClass, propertyName, msg); } + /** + * Create a new NullValueInNestedPathException. + * @param beanClass the offending bean class + * @param propertyName the offending property + * @param msg the detail message + * @param cause the root cause + * @since 4.3.2 + */ + public NullValueInNestedPathException(Class beanClass, String propertyName, String msg, Throwable cause) { + super(beanClass, propertyName, msg, cause); + } + } diff --git a/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java b/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java index 1d75c87a369..4d02d8d2a96 100644 --- a/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java +++ b/spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java @@ -36,6 +36,7 @@ import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; import org.springframework.util.ClassUtils; import org.springframework.util.NumberUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -543,7 +544,8 @@ class TypeConverterDelegate { convertedCopy = CollectionFactory.createApproximateCollection(original, original.size()); } else { - convertedCopy = (Collection) requiredType.newInstance(); + convertedCopy = (Collection) + ReflectionUtils.accessibleConstructor(requiredType).newInstance(); } } catch (Throwable ex) { @@ -625,7 +627,8 @@ class TypeConverterDelegate { convertedCopy = CollectionFactory.createApproximateMap(original, original.size()); } else { - convertedCopy = (Map) requiredType.newInstance(); + convertedCopy = (Map) + ReflectionUtils.accessibleConstructor(requiredType).newInstance(); } } catch (Throwable ex) { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java index 41653c8453c..cbb9d2f1536 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationSt Class subclass = createEnhancedSubclass(this.beanDefinition); Object instance; if (ctor == null) { - instance = BeanUtils.instantiate(subclass); + instance = BeanUtils.instantiateClass(subclass); } else { try { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java index 449e503f640..59fbdaac644 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java @@ -81,7 +81,7 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy { } bd.resolvedConstructorOrFactoryMethod = constructorToUse; } - catch (Exception ex) { + catch (Throwable ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java index 1cc067706c6..ced9aa043de 100644 --- a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java +++ b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java @@ -25,6 +25,8 @@ import java.util.List; import java.util.SortedSet; import java.util.TreeSet; +import org.springframework.util.ReflectionUtils; + /** * Property editor for Collections, converting any source Collection * to a given target Collection type. @@ -152,11 +154,11 @@ public class CustomCollectionEditor extends PropertyEditorSupport { protected Collection createCollection(Class collectionType, int initialCapacity) { if (!collectionType.isInterface()) { try { - return collectionType.newInstance(); + return ReflectionUtils.accessibleConstructor(collectionType).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException( - "Could not instantiate collection class [" + collectionType.getName() + "]: " + ex.getMessage()); + "Could not instantiate collection class: " + collectionType.getName(), ex); } } else if (List.class == collectionType) { diff --git a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java index e242b78c67d..afb393576a9 100644 --- a/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java +++ b/spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java @@ -22,6 +22,8 @@ import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; +import org.springframework.util.ReflectionUtils; + /** * Property editor for Maps, converting any source Map * to a given target Map type. @@ -130,11 +132,11 @@ public class CustomMapEditor extends PropertyEditorSupport { protected Map createMap(Class mapType, int initialCapacity) { if (!mapType.isInterface()) { try { - return mapType.newInstance(); + return ReflectionUtils.accessibleConstructor(mapType).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException( - "Could not instantiate map class [" + mapType.getName() + "]: " + ex.getMessage()); + "Could not instantiate map class: " + mapType.getName(), ex); } } else if (SortedMap.class == mapType) { diff --git a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java index 7aeb07d70ad..09cf9fbdb3a 100644 --- a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java +++ b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,8 @@ import org.quartz.SchedulerException; import org.quartz.spi.JobFactory; import org.quartz.spi.TriggerFiredBundle; +import org.springframework.util.ReflectionUtils; + /** * JobFactory implementation that supports {@link java.lang.Runnable} * objects as well as standard Quartz {@link org.quartz.Job} instances. @@ -55,7 +57,8 @@ public class AdaptableJobFactory implements JobFactory { * @throws Exception if job instantiation failed */ protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { - return bundle.getJobDetail().getJobClass().newInstance(); + Class jobClass = bundle.getJobDetail().getJobClass(); + return ReflectionUtils.accessibleConstructor(jobClass).newInstance(); } /** diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java index 26bf6849e91..d7c5afd3366 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,6 +40,7 @@ import org.springframework.core.type.filter.AspectJTypeFilter; import org.springframework.core.type.filter.AssignableTypeFilter; import org.springframework.core.type.filter.RegexPatternTypeFilter; import org.springframework.core.type.filter.TypeFilter; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -260,13 +261,13 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser { private Object instantiateUserDefinedStrategy(String className, Class strategyType, ClassLoader classLoader) { Object result; try { - result = classLoader.loadClass(className).newInstance(); + result = ReflectionUtils.accessibleConstructor(classLoader.loadClass(className)).newInstance(); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException("Class [" + className + "] for strategy [" + strategyType.getName() + "] not found", ex); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException("Unable to instantiate class [" + className + "] for strategy [" + strategyType.getName() + "]: a zero-argument constructor is required", ex); } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java index 541899aa8e6..73a57e8ce9e 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java @@ -466,9 +466,9 @@ class ConfigurationClassEnhancer { if (fbProxy == null) { try { - fbProxy = fbClass.newInstance(); + fbProxy = ReflectionUtils.accessibleConstructor(fbClass).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Unable to instantiate enhanced FactoryBean using Objenesis, " + "and regular FactoryBean instantiation via default constructor fails as well", ex); } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java index ce835bb7f05..1ad3157481d 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java @@ -379,7 +379,7 @@ class ConfigurationClassParser { Class factoryClass = propertySource.getClass("factory"); PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ? - DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiate(factoryClass)); + DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass)); for (String location : locations) { try { diff --git a/spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java b/spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java index bb0a0abd007..23d0d3a5e87 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java @@ -135,7 +135,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac if (ann == null) { return null; } - T bean = BeanUtils.instantiate(beanClass); + T bean = BeanUtils.instantiateClass(beanClass); AnnotationBeanUtils.copyPropertiesToBean(ann, bean); return bean; } diff --git a/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java index 44921c5282c..86d87d354e2 100644 --- a/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java +++ b/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java @@ -26,6 +26,7 @@ import org.springframework.scripting.ScriptFactory; import org.springframework.scripting.ScriptSource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * {@link org.springframework.scripting.ScriptFactory} implementation @@ -154,7 +155,7 @@ public class BshScriptFactory implements ScriptFactory, BeanClassLoaderAware { if (clazz != null) { // A Class: We need to create an instance for every call. try { - return clazz.newInstance(); + return ReflectionUtils.accessibleConstructor(clazz).newInstance(); } catch (Throwable ex) { throw new ScriptCompilationException( diff --git a/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java b/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java index 5fb732dc410..f7f634df2c6 100644 --- a/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java +++ b/spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java @@ -91,11 +91,10 @@ public abstract class BshScriptUtils { if (result instanceof Class) { Class clazz = (Class) result; try { - return clazz.newInstance(); + return ReflectionUtils.accessibleConstructor(clazz).newInstance(); } catch (Throwable ex) { - throw new IllegalStateException("Could not instantiate script class [" + - clazz.getName() + "]. Root cause is " + ex); + throw new IllegalStateException("Could not instantiate script class: " + clazz.getName(), ex); } } else { diff --git a/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java index 439f3c1e0e0..c0b1a5033d5 100644 --- a/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java +++ b/spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java @@ -17,6 +17,7 @@ package org.springframework.scripting.groovy; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; @@ -33,6 +34,7 @@ import org.springframework.scripting.ScriptFactory; import org.springframework.scripting.ScriptSource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * {@link org.springframework.scripting.ScriptFactory} implementation @@ -248,7 +250,7 @@ public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, Bea */ protected Object executeScript(ScriptSource scriptSource, Class scriptClass) throws ScriptCompilationException { try { - GroovyObject goo = (GroovyObject) scriptClass.newInstance(); + GroovyObject goo = (GroovyObject) ReflectionUtils.accessibleConstructor(scriptClass).newInstance(); if (this.groovyObjectCustomizer != null) { // Allow metaclass and other customization. @@ -264,14 +266,22 @@ public class GroovyScriptFactory implements ScriptFactory, BeanFactoryAware, Bea return goo; } } + catch (NoSuchMethodException ex) { + throw new ScriptCompilationException( + "No default constructor on Groovy script class: " + scriptClass.getName(), ex); + } catch (InstantiationException ex) { throw new ScriptCompilationException( - scriptSource, "Could not instantiate Groovy script class: " + scriptClass.getName(), ex); + scriptSource, "Unable to instantiate Groovy script class: " + scriptClass.getName(), ex); } catch (IllegalAccessException ex) { throw new ScriptCompilationException( scriptSource, "Could not access Groovy script constructor: " + scriptClass.getName(), ex); } + catch (InvocationTargetException ex) { + throw new ScriptCompilationException( + "Failed to invoke Groovy script constructor: " + scriptClass.getName(), ex.getTargetException()); + } } diff --git a/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java index bff51a79eaf..a823c54f3d9 100644 --- a/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java +++ b/spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.scripting.support; import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; @@ -28,6 +29,7 @@ import org.springframework.scripting.ScriptSource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -150,16 +152,24 @@ public class StandardScriptFactory implements ScriptFactory, BeanClassLoaderAwar if (script instanceof Class) { Class scriptClass = (Class) script; try { - return scriptClass.newInstance(); + return ReflectionUtils.accessibleConstructor(scriptClass).newInstance(); + } + catch (NoSuchMethodException ex) { + throw new ScriptCompilationException( + "No default constructor on script class: " + scriptClass.getName(), ex); } catch (InstantiationException ex) { throw new ScriptCompilationException( - scriptSource, "Could not instantiate script class: " + scriptClass.getName(), ex); + scriptSource, "Unable to instantiate script class: " + scriptClass.getName(), ex); } catch (IllegalAccessException ex) { throw new ScriptCompilationException( scriptSource, "Could not access script constructor: " + scriptClass.getName(), ex); } + catch (InvocationTargetException ex) { + throw new ScriptCompilationException( + "Failed to invoke script constructor: " + scriptClass.getName(), ex.getTargetException()); + } } return script; diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java index 07b7364152f..bcaadaaf71a 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java @@ -218,7 +218,7 @@ public class FormattingConversionServiceTests { assertEquals(new LocalDate(2009, 11, 1), new LocalDate(dates.get(1))); assertEquals(new LocalDate(2009, 11, 2), new LocalDate(dates.get(2))); - Object model = BeanUtils.instantiate(modelClass); + Object model = modelClass.newInstance(); ConfigurablePropertyAccessor accessor = directFieldAccess ? PropertyAccessorFactory.forDirectFieldAccess(model) : PropertyAccessorFactory.forBeanPropertyAccess(model); accessor.setConversionService(formattingService); diff --git a/spring-core/src/main/java/org/springframework/core/CollectionFactory.java b/spring-core/src/main/java/org/springframework/core/CollectionFactory.java index 060bf0c3e99..d64351441a2 100644 --- a/spring-core/src/main/java/org/springframework/core/CollectionFactory.java +++ b/spring-core/src/main/java/org/springframework/core/CollectionFactory.java @@ -38,6 +38,7 @@ import java.util.TreeSet; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import org.springframework.util.ReflectionUtils; /** * Factory for collections that is aware of Java 5, Java 6, and Spring @@ -201,9 +202,9 @@ public abstract class CollectionFactory { throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName()); } try { - return (Collection) collectionType.newInstance(); + return (Collection) ReflectionUtils.accessibleConstructor(collectionType).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException( "Could not instantiate Collection type: " + collectionType.getName(), ex); } @@ -316,9 +317,9 @@ public abstract class CollectionFactory { throw new IllegalArgumentException("Unsupported Map type: " + mapType.getName()); } try { - return (Map) mapType.newInstance(); + return (Map) ReflectionUtils.accessibleConstructor(mapType).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException("Could not instantiate Map type: " + mapType.getName(), ex); } } diff --git a/spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java b/spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java index 5af282f61d8..3af18e4c095 100644 --- a/spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java +++ b/spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -101,7 +101,7 @@ public class ConfigurableObjectInputStream extends ObjectInputStream { } } try { - return Proxy.getProxyClass(this.classLoader, resolvedInterfaces); + return ClassUtils.createCompositeInterface(resolvedInterfaces, this.classLoader); } catch (IllegalArgumentException ex) { throw new ClassNotFoundException(null, ex); @@ -117,7 +117,7 @@ public class ConfigurableObjectInputStream extends ObjectInputStream { for (int i = 0; i < interfaces.length; i++) { resolvedInterfaces[i] = resolveFallbackIfPossible(interfaces[i], ex); } - return Proxy.getProxyClass(getFallbackClassLoader(), resolvedInterfaces); + return ClassUtils.createCompositeInterface(resolvedInterfaces, getFallbackClassLoader()); } } } diff --git a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java index 57bf6e03410..ef4525214fa 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java @@ -17,7 +17,6 @@ package org.springframework.core.io.support; import java.io.IOException; -import java.lang.reflect.Constructor; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -134,12 +133,10 @@ public abstract class SpringFactoriesLoader { throw new IllegalArgumentException( "Class [" + instanceClassName + "] is not assignable to [" + factoryClass.getName() + "]"); } - Constructor constructor = instanceClass.getDeclaredConstructor(); - ReflectionUtils.makeAccessible(constructor); - return (T) constructor.newInstance(); + return (T) ReflectionUtils.accessibleConstructor(instanceClass).newInstance(); } catch (Throwable ex) { - throw new IllegalArgumentException("Cannot instantiate factory class: " + factoryClass.getName(), ex); + throw new IllegalArgumentException("Unable to instantiate factory class: " + factoryClass.getName(), ex); } } diff --git a/spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java b/spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java index 0d10f6a1f81..0c21234fe5c 100644 --- a/spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java +++ b/spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java @@ -17,6 +17,7 @@ package org.springframework.util; import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; @@ -264,13 +265,16 @@ public class AutoPopulatingList implements List, Serializable { public ElementInstantiationException(String msg) { super(msg); } + + public ElementInstantiationException(String message, Throwable cause) { + super(message, cause); + } } /** - * Reflective implementation of the ElementFactory interface, - * using {@code Class.newInstance()} on a given element class. - * @see Class#newInstance() + * Reflective implementation of the ElementFactory interface, using + * {@code Class.getDeclaredConstructor().newInstance()} on a given element class. */ private static class ReflectiveElementFactory implements ElementFactory, Serializable { @@ -286,15 +290,23 @@ public class AutoPopulatingList implements List, Serializable { @Override public E createElement(int index) { try { - return this.elementClass.newInstance(); + return ReflectionUtils.accessibleConstructor(this.elementClass).newInstance(); + } + catch (NoSuchMethodException ex) { + throw new ElementInstantiationException( + "No default constructor on element class: " + this.elementClass.getName(), ex); } catch (InstantiationException ex) { - throw new ElementInstantiationException("Unable to instantiate element class [" + - this.elementClass.getName() + "]. Root cause is " + ex); + throw new ElementInstantiationException( + "Unable to instantiate element class: " + this.elementClass.getName(), ex); } catch (IllegalAccessException ex) { - throw new ElementInstantiationException("Cannot access element class [" + - this.elementClass.getName() + "]. Root cause is " + ex); + throw new ElementInstantiationException( + "Could not access element constructor: " + this.elementClass.getName(), ex); + } + catch (InvocationTargetException ex) { + throw new ElementInstantiationException( + "Failed to invoke element constructor: " + this.elementClass.getName(), ex.getTargetException()); } } } diff --git a/spring-core/src/main/java/org/springframework/util/ClassUtils.java b/spring-core/src/main/java/org/springframework/util/ClassUtils.java index f867fe9aa37..1e6174585f0 100644 --- a/spring-core/src/main/java/org/springframework/util/ClassUtils.java +++ b/spring-core/src/main/java/org/springframework/util/ClassUtils.java @@ -1156,6 +1156,7 @@ public abstract class ClassUtils { * @return the merged interface as Class * @see java.lang.reflect.Proxy#getProxyClass */ + @SuppressWarnings("deprecation") public static Class createCompositeInterface(Class[] interfaces, ClassLoader classLoader) { Assert.notEmpty(interfaces, "Interfaces must not be empty"); Assert.notNull(classLoader, "ClassLoader must not be null"); diff --git a/spring-core/src/main/java/org/springframework/util/ReflectionUtils.java b/spring-core/src/main/java/org/springframework/util/ReflectionUtils.java index 9696faccd3a..934e92dca3a 100644 --- a/spring-core/src/main/java/org/springframework/util/ReflectionUtils.java +++ b/spring-core/src/main/java/org/springframework/util/ReflectionUtils.java @@ -476,6 +476,22 @@ public abstract class ReflectionUtils { } } + /** + * Obtain an accessible constructor for the given class and parameters. + * @param clazz the clazz to check + * @param parameterTypes the parameter types of the desired constructor + * @return the constructor reference + * @throws NoSuchMethodException if no such constructor exists + * @since 5.0 + */ + public static Constructor accessibleConstructor(Class clazz, Class... parameterTypes) + throws NoSuchMethodException { + + Constructor ctor = clazz.getDeclaredConstructor(parameterTypes); + makeAccessible(ctor); + return ctor; + } + /** * Perform the given callback operation on all matching methods of the given * class, as locally declared or equivalent thereof (such as default methods diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java index ae15a6f123d..05eb3a89988 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.support.ReflectivePropertyAccessor; +import org.springframework.util.ReflectionUtils; /** * An Indexer can index into some proceeding structure to access a particular piece of it. @@ -690,11 +691,11 @@ public class Indexer extends SpelNodeImpl { try { int newElements = this.index - this.collection.size(); while (newElements >= 0) { - (this.collection).add(elementType.getType().newInstance()); + (this.collection).add(ReflectionUtils.accessibleConstructor(elementType.getType()).newInstance()); newElements--; } } - catch (Exception ex) { + catch (Throwable ex) { throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION); } } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java index 67e2fc8fa16..18f68d190d9 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java @@ -16,6 +16,7 @@ package org.springframework.expression.spel.ast; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -34,6 +35,7 @@ import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.support.ReflectivePropertyAccessor; +import org.springframework.util.ReflectionUtils; /** * Represents a simple property or field reference. @@ -99,53 +101,34 @@ public class PropertyOrFieldReference extends SpelNodeImpl { TypeDescriptor resultDescriptor = result.getTypeDescriptor(); // Create a new collection or map ready for the indexer if (List.class == resultDescriptor.getType()) { - try { - if (isWritableProperty(this.name, contextObject, evalContext)) { - List newList = ArrayList.class.newInstance(); - writeProperty(contextObject, evalContext, this.name, newList); - result = readProperty(contextObject, evalContext, this.name); - } - } - catch (InstantiationException ex) { - throw new SpelEvaluationException(getStartPosition(), ex, - SpelMessage.UNABLE_TO_CREATE_LIST_FOR_INDEXING); - } - catch (IllegalAccessException ex) { - throw new SpelEvaluationException(getStartPosition(), ex, - SpelMessage.UNABLE_TO_CREATE_LIST_FOR_INDEXING); + if (isWritableProperty(this.name, contextObject, evalContext)) { + List newList = new ArrayList<>(); + writeProperty(contextObject, evalContext, this.name, newList); + result = readProperty(contextObject, evalContext, this.name); } } else if (Map.class == resultDescriptor.getType()) { - try { - if (isWritableProperty(this.name,contextObject, evalContext)) { - Map newMap = HashMap.class.newInstance(); - writeProperty(contextObject, evalContext, this.name, newMap); - result = readProperty(contextObject, evalContext, this.name); - } - } - catch (InstantiationException ex) { - throw new SpelEvaluationException(getStartPosition(), ex, - SpelMessage.UNABLE_TO_CREATE_MAP_FOR_INDEXING); - } - catch (IllegalAccessException ex) { - throw new SpelEvaluationException(getStartPosition(), ex, - SpelMessage.UNABLE_TO_CREATE_MAP_FOR_INDEXING); + if (isWritableProperty(this.name,contextObject, evalContext)) { + Map newMap = new HashMap<>(); + writeProperty(contextObject, evalContext, this.name, newMap); + result = readProperty(contextObject, evalContext, this.name); } } else { // 'simple' object try { if (isWritableProperty(this.name,contextObject, evalContext)) { - Object newObject = result.getTypeDescriptor().getType().newInstance(); + Class clazz = result.getTypeDescriptor().getType(); + Object newObject = ReflectionUtils.accessibleConstructor(clazz).newInstance(); writeProperty(contextObject, evalContext, this.name, newObject); result = readProperty(contextObject, evalContext, this.name); } } - catch (InstantiationException ex) { - throw new SpelEvaluationException(getStartPosition(), ex, + catch (InvocationTargetException ex) { + throw new SpelEvaluationException(getStartPosition(), ex.getTargetException(), SpelMessage.UNABLE_TO_DYNAMICALLY_CREATE_OBJECT, result.getTypeDescriptor().getType()); } - catch (IllegalAccessException ex) { + catch (Throwable ex) { throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_DYNAMICALLY_CREATE_OBJECT, result.getTypeDescriptor().getType()); } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java index 1af6019aac5..452c33b934b 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java @@ -37,6 +37,7 @@ import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.ast.SpelNodeImpl; import org.springframework.util.ClassUtils; import org.springframework.util.ConcurrentReferenceHashMap; +import org.springframework.util.ReflectionUtils; /** * A SpelCompiler will take a regular parsed expression and create (and load) a class @@ -105,7 +106,7 @@ public class SpelCompiler implements Opcodes { Class clazz = createExpressionClass(expression); if (clazz != null) { try { - return clazz.newInstance(); + return ReflectionUtils.accessibleConstructor(clazz).newInstance(); } catch (Throwable ex) { throw new IllegalStateException("Failed to instantiate CompiledExpression", ex); diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java index 331583633ee..7d4afa09c98 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java @@ -60,7 +60,7 @@ import org.springframework.util.StringUtils; *

To facilitate mapping between columns and fields that don't have matching names, * try using column aliases in the SQL statement like "select fname as first_name from customer". * - *

For 'null' values read from the databasem, we will attempt to call the setter, but in the case of + *

For 'null' values read from the database, we will attempt to call the setter, but in the case of * Java primitives, this causes a TypeMismatchException. This class can be configured (using the * primitivesDefaultedForNullValue property) to trap this exception and use the primitives default value. * Be aware that if you use the values from the generated bean to update the database the primitive value @@ -274,7 +274,7 @@ public class BeanPropertyRowMapper implements RowMapper { @Override public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); - T mappedObject = BeanUtils.instantiate(this.mappedClass); + T mappedObject = BeanUtils.instantiateClass(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java index 7a9c139973e..34e0cfe51a9 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.jdbc.support; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -190,9 +191,10 @@ public class SQLErrorCodes { public void setCustomSqlExceptionTranslatorClass(Class customTranslatorClass) { if (customTranslatorClass != null) { try { - this.customSqlExceptionTranslator = customTranslatorClass.newInstance(); + this.customSqlExceptionTranslator = + ReflectionUtils.accessibleConstructor(customTranslatorClass).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Unable to instantiate custom translator", ex); } } diff --git a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java index fd166d91084..1c3c59c51d2 100644 --- a/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java +++ b/spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java @@ -427,7 +427,7 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC catch (Throwable ex) { throw new BeanInitializationException("Could not find default validator class", ex); } - validator = (Validator) BeanUtils.instantiate(clazz); + validator = (Validator) BeanUtils.instantiateClass(clazz); } else { validator = new Validator() { diff --git a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java index e198d10bc9f..f213dcf24e8 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java @@ -76,7 +76,6 @@ import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.InitializingBean; @@ -545,6 +544,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, Generi } } + @SuppressWarnings("deprecation") private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException { if (logger.isDebugEnabled()) { logger.debug("Setting validation schema to " + @@ -553,7 +553,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, Generi Assert.notEmpty(resources, "No resources given"); Assert.hasLength(schemaLanguage, "No schema language provided"); Source[] schemaSources = new Source[resources.length]; - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); for (int i = 0; i < resources.length; i++) { Assert.notNull(resources[i], "Resource is null"); @@ -805,6 +805,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, Generi } } + @SuppressWarnings("deprecation") private Source processSource(Source source) { if (StaxUtils.isStaxSource(source) || source instanceof DOMSource) { return source; @@ -833,7 +834,7 @@ public class Jaxb2Marshaller implements MimeMarshaller, MimeUnmarshaller, Generi try { if (xmlReader == null) { - xmlReader = XMLReaderFactory.createXMLReader(); + xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); } xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); String name = "http://xml.org/sax/features/external-general-entities"; diff --git a/spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java index 8b92f1c0421..6c2d43982a2 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java @@ -49,7 +49,6 @@ import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; -import org.xml.sax.helpers.XMLReaderFactory; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; @@ -184,8 +183,9 @@ public abstract class AbstractMarshaller implements Marshaller, Unmarshaller { * @return the XMLReader * @throws SAXException if thrown by JAXP methods */ + @SuppressWarnings("deprecation") protected XMLReader createXmlReader() throws SAXException { - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { diff --git a/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java b/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java index 45cd2d82edf..2a52f414760 100644 --- a/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java +++ b/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java @@ -28,6 +28,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * Simple implementation of a JNDI naming context builder. @@ -210,10 +211,10 @@ public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder "Specified class does not implement [" + InitialContextFactory.class.getName() + "]: " + icf); } try { - return (InitialContextFactory) icfClass.newInstance(); + return (InitialContextFactory) ReflectionUtils.accessibleConstructor(icfClass).newInstance(); } catch (Throwable ex) { - throw new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf, ex); + throw new IllegalStateException("Unable to instantiate specified InitialContextFactory: " + icf, ex); } } } diff --git a/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java b/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java index ce30ca480c0..21cfcb14c85 100644 --- a/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java +++ b/spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java @@ -25,6 +25,7 @@ import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -87,7 +88,7 @@ public abstract class ProfileValueUtils { } else { try { - profileValueSource = profileValueSourceType.newInstance(); + profileValueSource = ReflectionUtils.accessibleConstructor(profileValueSourceType).newInstance(); } catch (Exception ex) { if (logger.isWarnEnabled()) { diff --git a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java index 9506223a72a..600c8e921e3 100644 --- a/spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java +++ b/spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -366,17 +366,17 @@ class StubWebApplicationContext implements WebApplicationContext { @Override public T createBean(Class beanClass) { - return BeanUtils.instantiate(beanClass); + return BeanUtils.instantiateClass(beanClass); } @Override public Object createBean(Class beanClass, int autowireMode, boolean dependencyCheck) { - return BeanUtils.instantiate(beanClass); + return BeanUtils.instantiateClass(beanClass); } @Override public Object autowire(Class beanClass, int autowireMode, boolean dependencyCheck) { - return BeanUtils.instantiate(beanClass); + return BeanUtils.instantiateClass(beanClass); } @Override diff --git a/spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java b/spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java index 5e0a1639575..dd1e0779b4d 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java +++ b/spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +59,7 @@ public class JtaTransactionManagerFactoryBean implements FactoryBean clazz = (Class) ClassUtils.forName(className, JtaTransactionManagerFactoryBean.class.getClassLoader()); - this.transactionManager = BeanUtils.instantiate(clazz); + this.transactionManager = BeanUtils.instantiateClass(clazz); } catch (ClassNotFoundException ex) { throw new IllegalStateException("Failed to load JtaTransactionManager class: " + className, ex); diff --git a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java index 49ef68864dd..b06b6637dff 100644 --- a/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java +++ b/spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.reactive.config; import java.util.ArrayList; @@ -73,18 +74,18 @@ import org.springframework.web.reactive.result.view.ViewResolver; * @author Rossen Stoyanchev * @since 5.0 */ -@Configuration @SuppressWarnings("unused") +@Configuration public class WebReactiveConfiguration implements ApplicationContextAware { - private static final ClassLoader classLoader = WebReactiveConfiguration.class.getClassLoader(); - private static final boolean jackson2Present = - ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && - ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); + ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebReactiveConfiguration.class.getClassLoader()) && + ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebReactiveConfiguration.class.getClassLoader()); - private static final boolean jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader); + private static final boolean jaxb2Present = + ClassUtils.isPresent("javax.xml.bind.Binder", WebReactiveConfiguration.class.getClassLoader()); - private static final boolean rxJava1Present = ClassUtils.isPresent("rx.Observable", classLoader); + private static final boolean rxJava1Present = + ClassUtils.isPresent("rx.Observable", WebReactiveConfiguration.class.getClassLoader()); private PathMatchConfigurer pathMatchConfigurer; @@ -302,7 +303,7 @@ public class WebReactiveConfiguration implements ApplicationContextAware { Class clazz; try { String name = "org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean"; - clazz = ClassUtils.forName(name, classLoader); + clazz = ClassUtils.forName(name, getClass().getClassLoader()); } catch (ClassNotFoundException ex) { throw new BeanInitializationException("Could not find default validator class", ex); @@ -310,7 +311,7 @@ public class WebReactiveConfiguration implements ApplicationContextAware { catch (LinkageError ex) { throw new BeanInitializationException("Could not load default validator class", ex); } - validator = (Validator) BeanUtils.instantiate(clazz); + validator = (Validator) BeanUtils.instantiateClass(clazz); } else { validator = new NoOpValidator(); @@ -401,7 +402,7 @@ public class WebReactiveConfiguration implements ApplicationContextAware { @Bean public ViewResolutionResultHandler viewResolutionResultHandler() { - ViewResolverRegistry registry = new ViewResolverRegistry(this.applicationContext); + ViewResolverRegistry registry = new ViewResolverRegistry(getApplicationContext()); configureViewResolvers(registry); List resolvers = registry.getViewResolvers(); ViewResolutionResultHandler handler = new ViewResolutionResultHandler(resolvers, mvcConversionService()); diff --git a/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java b/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java index 77ed24fcdb1..ff8e905a5cd 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java +++ b/spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java @@ -615,7 +615,7 @@ public class Jackson2ObjectMapperBuilder { } if (this.moduleClasses != null) { for (Class module : this.moduleClasses) { - objectMapper.registerModule(BeanUtils.instantiate(module)); + objectMapper.registerModule(BeanUtils.instantiateClass(module)); } } @@ -723,7 +723,7 @@ public class Jackson2ObjectMapperBuilder { try { Class jdk7Module = (Class) ClassUtils.forName("com.fasterxml.jackson.datatype.jdk7.Jdk7Module", this.moduleClassLoader); - objectMapper.registerModule(BeanUtils.instantiate(jdk7Module)); + objectMapper.registerModule(BeanUtils.instantiateClass(jdk7Module)); } catch (ClassNotFoundException ex) { // jackson-datatype-jdk7 not available @@ -732,7 +732,7 @@ public class Jackson2ObjectMapperBuilder { try { Class jdk8Module = (Class) ClassUtils.forName("com.fasterxml.jackson.datatype.jdk8.Jdk8Module", this.moduleClassLoader); - objectMapper.registerModule(BeanUtils.instantiate(jdk8Module)); + objectMapper.registerModule(BeanUtils.instantiateClass(jdk8Module)); } catch (ClassNotFoundException ex) { // jackson-datatype-jdk8 not available @@ -743,7 +743,7 @@ public class Jackson2ObjectMapperBuilder { try { Class javaTimeModule = (Class) ClassUtils.forName("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", this.moduleClassLoader); - objectMapper.registerModule(BeanUtils.instantiate(javaTimeModule)); + objectMapper.registerModule(BeanUtils.instantiateClass(javaTimeModule)); } catch (ClassNotFoundException ex) { // jackson-datatype-jsr310 not available @@ -755,7 +755,7 @@ public class Jackson2ObjectMapperBuilder { try { Class jodaModule = (Class) ClassUtils.forName("com.fasterxml.jackson.datatype.joda.JodaModule", this.moduleClassLoader); - objectMapper.registerModule(BeanUtils.instantiate(jodaModule)); + objectMapper.registerModule(BeanUtils.instantiateClass(jodaModule)); } catch (ClassNotFoundException ex) { // jackson-datatype-joda not available @@ -767,7 +767,7 @@ public class Jackson2ObjectMapperBuilder { try { Class kotlinModule = (Class) ClassUtils.forName("com.fasterxml.jackson.module.kotlin.KotlinModule", this.moduleClassLoader); - objectMapper.registerModule(BeanUtils.instantiate(kotlinModule)); + objectMapper.registerModule(BeanUtils.instantiateClass(kotlinModule)); } catch (ClassNotFoundException ex) { // jackson-module-kotlin not available diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java index 91bc8f27154..884a53b34d2 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,6 +45,7 @@ import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConversionException; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StreamUtils; /** @@ -185,12 +186,11 @@ public class Jaxb2CollectionHttpMessageConverter protected T createCollection(Class collectionClass) { if (!collectionClass.isInterface()) { try { - return (T) collectionClass.newInstance(); + return (T) ReflectionUtils.accessibleConstructor(collectionClass).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalArgumentException( - "Could not instantiate collection class [" + - collectionClass.getName() + "]: " + ex.getMessage()); + "Could not instantiate collection class: " + collectionClass.getName(), ex); } } else if (List.class == collectionClass) { diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java index 5be9e392c9d..7b05bfb198d 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,6 @@ import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.HttpHeaders; @@ -154,12 +153,13 @@ public class Jaxb2RootElementHttpMessageConverter extends AbstractJaxb2HttpMessa } } + @SuppressWarnings("deprecation") protected Source processSource(Source source) { if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; InputSource inputSource = new InputSource(streamSource.getInputStream()); try { - XMLReader xmlReader = XMLReaderFactory.createXMLReader(); + XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); String featureName = "http://xml.org/sax/features/external-general-entities"; xmlReader.setFeature(featureName, isProcessExternalEntities()); diff --git a/spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java index a4a2f29572f..1f4898e9660 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java @@ -45,7 +45,6 @@ import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; @@ -189,16 +188,17 @@ public class SourceHttpMessageConverter extends AbstractHttpMe } } + @SuppressWarnings("deprecation") private SAXSource readSAXSource(InputStream body) throws IOException { try { - XMLReader reader = XMLReaderFactory.createXMLReader(); - reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); - reader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); + XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); + xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd()); + xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities()); if (!isProcessExternalEntities()) { - reader.setEntityResolver(NO_OP_ENTITY_RESOLVER); + xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER); } byte[] bytes = StreamUtils.copyToByteArray(body); - return new SAXSource(reader, new InputSource(new ByteArrayInputStream(bytes))); + return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes))); } catch (SAXException ex) { throw new HttpMessageNotReadableException("Could not parse document: " + ex.getMessage(), ex); diff --git a/spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java b/spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java index acd7a3d679a..d0cce7d6acb 100644 --- a/spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java +++ b/spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java @@ -27,6 +27,7 @@ import javax.servlet.ServletException; import javax.servlet.annotation.HandlesTypes; import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.util.ReflectionUtils; /** * Servlet 3.0 {@link ServletContainerInitializer} designed to support code-based @@ -149,7 +150,8 @@ public class SpringServletContainerInitializer implements ServletContainerInitia if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { - initializers.add((WebApplicationInitializer) waiClass.newInstance()); + initializers.add((WebApplicationInitializer) + ReflectionUtils.accessibleConstructor(waiClass).newInstance()); } catch (Throwable ex) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex); diff --git a/spring-web/src/main/java/org/springframework/web/util/WebUtils.java b/spring-web/src/main/java/org/springframework/web/util/WebUtils.java index 17a9a56b368..65a97801b53 100644 --- a/spring-web/src/main/java/org/springframework/web/util/WebUtils.java +++ b/spring-web/src/main/java/org/springframework/web/util/WebUtils.java @@ -326,40 +326,6 @@ public abstract class WebUtils { } } - /** - * Get the specified session attribute, creating and setting a new attribute if - * no existing found. The given class needs to have a public no-arg constructor. - * Useful for on-demand state objects in a web tier, like shopping carts. - * @param session current HTTP session - * @param name the name of the session attribute - * @param clazz the class to instantiate for a new attribute - * @return the value of the session attribute, newly created if not found - * @throws IllegalArgumentException if the session attribute could not be instantiated - */ - public static Object getOrCreateSessionAttribute(HttpSession session, String name, Class clazz) - throws IllegalArgumentException { - - Assert.notNull(session, "Session must not be null"); - Object sessionObject = session.getAttribute(name); - if (sessionObject == null) { - try { - sessionObject = clazz.newInstance(); - } - catch (InstantiationException ex) { - throw new IllegalArgumentException( - "Could not instantiate class [" + clazz.getName() + - "] for session attribute '" + name + "': " + ex.getMessage()); - } - catch (IllegalAccessException ex) { - throw new IllegalArgumentException( - "Could not access default constructor of class [" + clazz.getName() + - "] for session attribute '" + name + "': " + ex.getMessage()); - } - session.setAttribute(name, sessionObject); - } - return sessionObject; - } - /** * Return the best available mutex for the given session: * that is, an object to synchronize on for the given session. diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java index f58e5bdcdd6..389ffd87540 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java @@ -567,7 +567,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv catch (LinkageError ex) { throw new BeanInitializationException("Could not load default validator class", ex); } - validator = (Validator) BeanUtils.instantiate(clazz); + validator = (Validator) BeanUtils.instantiateClass(clazz); } else { validator = new NoOpValidator(); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java index d50ef66fdf7..182a9037e27 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; +import org.springframework.util.ReflectionUtils; import org.springframework.web.servlet.ModelAndView; /** @@ -78,13 +79,11 @@ import org.springframework.web.servlet.ModelAndView; * @author Juergen Hoeller * @since 1.1.1 * @see ServletForwardingController - * @see org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor - * @see org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter */ public class ServletWrappingController extends AbstractController implements BeanNameAware, InitializingBean, DisposableBean { - private Class servletClass; + private Class servletClass; private String servletName; @@ -105,7 +104,7 @@ public class ServletWrappingController extends AbstractController * Needs to implement {@code javax.servlet.Servlet}. * @see javax.servlet.Servlet */ - public void setServletClass(Class servletClass) { + public void setServletClass(Class servletClass) { this.servletClass = servletClass; } @@ -142,12 +141,12 @@ public class ServletWrappingController extends AbstractController } if (!Servlet.class.isAssignableFrom(this.servletClass)) { throw new IllegalArgumentException("servletClass [" + this.servletClass.getName() + - "] needs to implement interface [javax.servlet.Servlet]"); + "] needs to implement interface [javax.servlet.Servlet]"); } if (this.servletName == null) { this.servletName = this.beanName; } - this.servletInstance = (Servlet) this.servletClass.newInstance(); + this.servletInstance = ReflectionUtils.accessibleConstructor(this.servletClass).newInstance(); this.servletInstance.init(new DelegatingServletConfig()); } @@ -158,7 +157,7 @@ public class ServletWrappingController extends AbstractController */ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) - throws Exception { + throws Exception { this.servletInstance.service(request, response); return null; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java index aefc71b61ad..e2031f67e1b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java @@ -612,9 +612,9 @@ public class MvcUriComponentsBuilder { if (proxy == null) { try { - proxy = proxyClass.newInstance(); + proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance(); } - catch (Exception ex) { + catch (Throwable ex) { throw new IllegalStateException("Unable to instantiate controller proxy using Objenesis, " + "and regular controller instantiation via default constructor fails as well", ex); } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java index 9e65987c551..a2aec332983 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java @@ -336,7 +336,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D LocaleResolver resolver) { if (definitionsFactoryClass != null) { - DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass); + DefinitionsFactory factory = BeanUtils.instantiateClass(definitionsFactoryClass); if (factory instanceof ApplicationContextAware) { ((ApplicationContextAware) factory).setApplicationContext(applicationContext); } @@ -357,7 +357,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D @Override protected PreparerFactory createPreparerFactory(ApplicationContext context) { if (preparerFactoryClass != null) { - return BeanUtils.instantiate(preparerFactoryClass); + return BeanUtils.instantiateClass(preparerFactoryClass); } else { return super.createPreparerFactory(context); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java index 35587b78c44..1ddd7fee2c7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,6 +46,7 @@ import org.springframework.context.ApplicationContextException; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import org.springframework.util.xml.SimpleTransformErrorListener; import org.springframework.util.xml.TransformerUtils; @@ -73,7 +74,7 @@ import org.springframework.web.util.WebUtils; */ public class XsltView extends AbstractUrlBasedView { - private Class transformerFactoryClass; + private Class transformerFactoryClass; private String sourceKey; @@ -97,7 +98,7 @@ public class XsltView extends AbstractUrlBasedView { *

The default constructor of the specified class will be called * to build the TransformerFactory for this view. */ - public void setTransformerFactoryClass(Class transformerFactoryClass) { + public void setTransformerFactoryClass(Class transformerFactoryClass) { Assert.isAssignable(TransformerFactory.class, transformerFactoryClass); this.transformerFactoryClass = transformerFactoryClass; } @@ -195,10 +196,10 @@ public class XsltView extends AbstractUrlBasedView { * @see #setTransformerFactoryClass * @see #getTransformerFactory() */ - protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { + protected TransformerFactory newTransformerFactory(Class transformerFactoryClass) { if (transformerFactoryClass != null) { try { - return (TransformerFactory) transformerFactoryClass.newInstance(); + return ReflectionUtils.accessibleConstructor(transformerFactoryClass).newInstance(); } catch (Exception ex) { throw new TransformerFactoryConfigurationError(ex, "Could not instantiate TransformerFactory"); diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java b/spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java index 7169c253e94..4ef9815b51d 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ public class BeanCreatingHandlerProvider implements BeanFactoryAware { return this.beanFactory.createBean(this.handlerType); } else { - return BeanUtils.instantiate(this.handlerType); + return BeanUtils.instantiateClass(this.handlerType); } } diff --git a/spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java b/spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java index 4847c115739..e79a239d795 100644 --- a/spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java +++ b/spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java @@ -35,6 +35,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.socket.SubProtocolCapable; import org.springframework.web.socket.WebSocketExtension; @@ -72,25 +73,23 @@ public abstract class AbstractHandshakeHandler implements HandshakeHandler, Life private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); - private static final ClassLoader classLoader = AbstractHandshakeHandler.class.getClassLoader(); - private static final boolean jettyWsPresent = ClassUtils.isPresent( - "org.eclipse.jetty.websocket.server.WebSocketServerFactory", classLoader); + "org.eclipse.jetty.websocket.server.WebSocketServerFactory", AbstractHandshakeHandler.class.getClassLoader()); private static final boolean tomcatWsPresent = ClassUtils.isPresent( - "org.apache.tomcat.websocket.server.WsHttpUpgradeHandler", classLoader); + "org.apache.tomcat.websocket.server.WsHttpUpgradeHandler", AbstractHandshakeHandler.class.getClassLoader()); private static final boolean undertowWsPresent = ClassUtils.isPresent( - "io.undertow.websockets.jsr.ServerWebSocketContainer", classLoader); + "io.undertow.websockets.jsr.ServerWebSocketContainer", AbstractHandshakeHandler.class.getClassLoader()); private static final boolean glassfishWsPresent = ClassUtils.isPresent( - "org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler", classLoader); + "org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler", AbstractHandshakeHandler.class.getClassLoader()); private static final boolean weblogicWsPresent = ClassUtils.isPresent( - "weblogic.websocket.tyrus.TyrusServletWriter", classLoader); + "weblogic.websocket.tyrus.TyrusServletWriter", AbstractHandshakeHandler.class.getClassLoader()); private static final boolean websphereWsPresent = ClassUtils.isPresent( - "com.ibm.websphere.wsoc.WsWsocServerContainer", classLoader); + "com.ibm.websphere.wsoc.WsWsocServerContainer", AbstractHandshakeHandler.class.getClassLoader()); protected final Log logger = LogFactory.getLog(getClass()); @@ -146,8 +145,8 @@ public abstract class AbstractHandshakeHandler implements HandshakeHandler, Life } try { - Class clazz = ClassUtils.forName(className, classLoader); - return (RequestUpgradeStrategy) clazz.newInstance(); + Class clazz = ClassUtils.forName(className, AbstractHandshakeHandler.class.getClassLoader()); + return (RequestUpgradeStrategy) ReflectionUtils.accessibleConstructor(clazz).newInstance(); } catch (Throwable ex) { throw new IllegalStateException(