Browse Source

Consistently use constructor-based instantiation instead of Class.newInstance / BeanUtils.instantiate

Issue: SPR-14486
pull/1119/head
Juergen Hoeller 10 years ago
parent
commit
aaac199e8b
  1. 21
      spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java
  2. 16
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java
  3. 12
      spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java
  4. 3
      spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java
  5. 14
      spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java
  6. 28
      spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
  7. 15
      spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java
  8. 7
      spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java
  9. 4
      spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java
  10. 2
      spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java
  11. 8
      spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java
  12. 8
      spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java
  13. 7
      spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java
  14. 7
      spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java
  15. 4
      spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
  16. 2
      spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
  17. 2
      spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java
  18. 3
      spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java
  19. 5
      spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java
  20. 14
      spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java
  21. 16
      spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java
  22. 2
      spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java
  23. 9
      spring-core/src/main/java/org/springframework/core/CollectionFactory.java
  24. 6
      spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java
  25. 7
      spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java
  26. 28
      spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java
  27. 1
      spring-core/src/main/java/org/springframework/util/ClassUtils.java
  28. 16
      spring-core/src/main/java/org/springframework/util/ReflectionUtils.java
  29. 7
      spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
  30. 47
      spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java
  31. 3
      spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java
  32. 4
      spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java
  33. 8
      spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java
  34. 2
      spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java
  35. 7
      spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java
  36. 4
      spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java
  37. 5
      spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java
  38. 3
      spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java
  39. 8
      spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java
  40. 4
      spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java
  41. 21
      spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java
  42. 12
      spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java
  43. 10
      spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java
  44. 6
      spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java
  45. 12
      spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java
  46. 4
      spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java
  47. 34
      spring-web/src/main/java/org/springframework/web/util/WebUtils.java
  48. 2
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
  49. 15
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java
  50. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java
  51. 4
      spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java
  52. 11
      spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java
  53. 4
      spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java
  54. 19
      spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java

21
spring-aop/src/main/java/org/springframework/aop/aspectj/SimpleAspectInstanceFactory.java

@ -1,5 +1,5 @@ @@ -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 @@ @@ -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 { @@ -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());
}
}

16
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectJProxyFactory.java

@ -24,7 +24,7 @@ import org.aspectj.lang.reflect.PerClauseKind; @@ -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 { @@ -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;
}
}

12
spring-aop/src/main/java/org/springframework/aop/framework/ObjenesisCglibAopProxy.java

@ -1,5 +1,5 @@ @@ -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 @@ @@ -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; @@ -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 { @@ -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, " +

3
spring-aop/src/main/java/org/springframework/aop/support/DelegatePerTargetObjectIntroductionInterceptor.java

@ -24,6 +24,7 @@ import org.aopalliance.intercept.MethodInvocation; @@ -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 @@ -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 '" +

14
spring-beans/src/main/java/org/springframework/beans/AbstractNestablePropertyAccessor.java

@ -18,7 +18,9 @@ package org.springframework.beans; @@ -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 @@ -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);
}
}

28
spring-beans/src/main/java/org/springframework/beans/BeanUtils.java

@ -63,12 +63,14 @@ public abstract class BeanUtils { @@ -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> T instantiate(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
@ -87,13 +89,12 @@ public abstract class BeanUtils { @@ -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.
* <p>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> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
@ -111,17 +112,15 @@ public abstract class BeanUtils { @@ -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.
* <p>Useful in cases where
* the type of the class to instantiate (clazz) is not available, but the type
* desired (assignableTo) is known.
* <p>As this method doesn't try to load classes by name, it should avoid
* class-loading issues.
* <p>Note that this method tries to set the constructor accessible
* if given a non-accessible (that is, non-public) constructor.
* <p>Useful in cases where the type of the class to instantiate (clazz) is not
* available, but the type desired (assignableTo) is known.
* <p>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> T instantiateClass(Class<?> clazz, Class<T> assignableTo) throws BeanInstantiationException {
@ -131,14 +130,13 @@ public abstract class BeanUtils { @@ -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.
* <p>Note that this method tries to set the constructor accessible
* if given a non-accessible (that is, non-public) constructor.
* <p>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> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");

15
spring-beans/src/main/java/org/springframework/beans/NullValueInNestedPathException.java

@ -1,5 +1,5 @@ @@ -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; @@ -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 { @@ -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);
}
}

7
spring-beans/src/main/java/org/springframework/beans/TypeConverterDelegate.java

@ -36,6 +36,7 @@ import org.springframework.core.convert.ConversionService; @@ -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 { @@ -543,7 +544,8 @@ class TypeConverterDelegate {
convertedCopy = CollectionFactory.createApproximateCollection(original, original.size());
}
else {
convertedCopy = (Collection<Object>) requiredType.newInstance();
convertedCopy = (Collection<Object>)
ReflectionUtils.accessibleConstructor(requiredType).newInstance();
}
}
catch (Throwable ex) {
@ -625,7 +627,8 @@ class TypeConverterDelegate { @@ -625,7 +627,8 @@ class TypeConverterDelegate {
convertedCopy = CollectionFactory.createApproximateMap(original, original.size());
}
else {
convertedCopy = (Map<Object, Object>) requiredType.newInstance();
convertedCopy = (Map<Object, Object>)
ReflectionUtils.accessibleConstructor(requiredType).newInstance();
}
}
catch (Throwable ex) {

4
spring-beans/src/main/java/org/springframework/beans/factory/support/CglibSubclassingInstantiationStrategy.java

@ -1,5 +1,5 @@ @@ -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 @@ -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 {

2
spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java

@ -81,7 +81,7 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy { @@ -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);
}
}

8
spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomCollectionEditor.java

@ -25,6 +25,8 @@ import java.util.List; @@ -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 { @@ -152,11 +154,11 @@ public class CustomCollectionEditor extends PropertyEditorSupport {
protected Collection<Object> createCollection(Class<? extends Collection> 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) {

8
spring-beans/src/main/java/org/springframework/beans/propertyeditors/CustomMapEditor.java

@ -22,6 +22,8 @@ import java.util.Map; @@ -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 { @@ -130,11 +132,11 @@ public class CustomMapEditor extends PropertyEditorSupport {
protected Map<Object, Object> createMap(Class<? extends Map> 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) {

7
spring-context-support/src/main/java/org/springframework/scheduling/quartz/AdaptableJobFactory.java

@ -1,5 +1,5 @@ @@ -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; @@ -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 { @@ -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();
}
/**

7
spring-context/src/main/java/org/springframework/context/annotation/ComponentScanBeanDefinitionParser.java

@ -1,5 +1,5 @@ @@ -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; @@ -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 { @@ -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);
}

4
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java

@ -466,9 +466,9 @@ class ConfigurationClassEnhancer { @@ -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);
}

2
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java

@ -379,7 +379,7 @@ class ConfigurationClassParser { @@ -379,7 +379,7 @@ class ConfigurationClassParser {
Class<? extends PropertySourceFactory> 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 {

2
spring-context/src/main/java/org/springframework/jmx/export/annotation/AnnotationJmxAttributeSource.java

@ -135,7 +135,7 @@ public class AnnotationJmxAttributeSource implements JmxAttributeSource, BeanFac @@ -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;
}

3
spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java

@ -26,6 +26,7 @@ import org.springframework.scripting.ScriptFactory; @@ -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 { @@ -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(

5
spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptUtils.java

@ -91,11 +91,10 @@ public abstract class BshScriptUtils { @@ -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 {

14
spring-context/src/main/java/org/springframework/scripting/groovy/GroovyScriptFactory.java

@ -17,6 +17,7 @@ @@ -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; @@ -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 @@ -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 @@ -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());
}
}

16
spring-context/src/main/java/org/springframework/scripting/support/StandardScriptFactory.java

@ -1,5 +1,5 @@ @@ -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 @@ @@ -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; @@ -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 @@ -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;

2
spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java

@ -218,7 +218,7 @@ public class FormattingConversionServiceTests { @@ -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);

9
spring-core/src/main/java/org/springframework/core/CollectionFactory.java

@ -38,6 +38,7 @@ import java.util.TreeSet; @@ -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 { @@ -201,9 +202,9 @@ public abstract class CollectionFactory {
throw new IllegalArgumentException("Unsupported Collection type: " + collectionType.getName());
}
try {
return (Collection<E>) collectionType.newInstance();
return (Collection<E>) 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 { @@ -316,9 +317,9 @@ public abstract class CollectionFactory {
throw new IllegalArgumentException("Unsupported Map type: " + mapType.getName());
}
try {
return (Map<K, V>) mapType.newInstance();
return (Map<K, V>) ReflectionUtils.accessibleConstructor(mapType).newInstance();
}
catch (Exception ex) {
catch (Throwable ex) {
throw new IllegalArgumentException("Could not instantiate Map type: " + mapType.getName(), ex);
}
}

6
spring-core/src/main/java/org/springframework/core/ConfigurableObjectInputStream.java

@ -1,5 +1,5 @@ @@ -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 { @@ -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 { @@ -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());
}
}
}

7
spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java

@ -17,7 +17,6 @@ @@ -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 { @@ -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);
}
}

28
spring-core/src/main/java/org/springframework/util/AutoPopulatingList.java

@ -17,6 +17,7 @@ @@ -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<E> implements List<E>, Serializable { @@ -264,13 +265,16 @@ public class AutoPopulatingList<E> implements List<E>, 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<E> implements ElementFactory<E>, Serializable {
@ -286,15 +290,23 @@ public class AutoPopulatingList<E> implements List<E>, Serializable { @@ -286,15 +290,23 @@ public class AutoPopulatingList<E> implements List<E>, 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());
}
}
}

1
spring-core/src/main/java/org/springframework/util/ClassUtils.java

@ -1156,6 +1156,7 @@ public abstract class ClassUtils { @@ -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");

16
spring-core/src/main/java/org/springframework/util/ReflectionUtils.java

@ -476,6 +476,22 @@ public abstract class ReflectionUtils { @@ -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 <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
throws NoSuchMethodException {
Constructor<T> 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

7
spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java

@ -1,5 +1,5 @@ @@ -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; @@ -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 { @@ -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);
}
}

47
spring-expression/src/main/java/org/springframework/expression/spel/ast/PropertyOrFieldReference.java

@ -16,6 +16,7 @@ @@ -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; @@ -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 { @@ -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());
}

3
spring-expression/src/main/java/org/springframework/expression/spel/standard/SpelCompiler.java

@ -37,6 +37,7 @@ import org.springframework.expression.spel.SpelParserConfiguration; @@ -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 { @@ -105,7 +106,7 @@ public class SpelCompiler implements Opcodes {
Class<? extends CompiledExpression> 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);

4
spring-jdbc/src/main/java/org/springframework/jdbc/core/BeanPropertyRowMapper.java

@ -60,7 +60,7 @@ import org.springframework.util.StringUtils; @@ -60,7 +60,7 @@ import org.springframework.util.StringUtils;
* <p>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".
*
* <p>For 'null' values read from the databasem, we will attempt to call the setter, but in the case of
* <p>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<T> implements RowMapper<T> { @@ -274,7 +274,7 @@ public class BeanPropertyRowMapper<T> implements RowMapper<T> {
@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);

8
spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodes.java

@ -1,5 +1,5 @@ @@ -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 @@ @@ -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 { @@ -190,9 +191,10 @@ public class SQLErrorCodes {
public void setCustomSqlExceptionTranslatorClass(Class<? extends SQLExceptionTranslator> 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);
}
}

2
spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java

@ -427,7 +427,7 @@ public abstract class AbstractMessageBrokerConfiguration implements ApplicationC @@ -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() {

7
spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java

@ -76,7 +76,6 @@ import org.xml.sax.EntityResolver; @@ -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 @@ -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 @@ -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 @@ -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 @@ -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";

4
spring-oxm/src/main/java/org/springframework/oxm/support/AbstractMarshaller.java

@ -49,7 +49,6 @@ import org.xml.sax.InputSource; @@ -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 { @@ -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()) {

5
spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java

@ -28,6 +28,7 @@ import org.apache.commons.logging.LogFactory; @@ -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 @@ -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);
}
}
}

3
spring-test/src/main/java/org/springframework/test/annotation/ProfileValueUtils.java

@ -25,6 +25,7 @@ import org.springframework.core.annotation.AnnotatedElementUtils; @@ -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 { @@ -87,7 +88,7 @@ public abstract class ProfileValueUtils {
}
else {
try {
profileValueSource = profileValueSourceType.newInstance();
profileValueSource = ReflectionUtils.accessibleConstructor(profileValueSourceType).newInstance();
}
catch (Exception ex) {
if (logger.isWarnEnabled()) {

8
spring-test/src/main/java/org/springframework/test/web/servlet/setup/StubWebApplicationContext.java

@ -1,5 +1,5 @@ @@ -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 { @@ -366,17 +366,17 @@ class StubWebApplicationContext implements WebApplicationContext {
@Override
public <T> T createBean(Class<T> 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

4
spring-tx/src/main/java/org/springframework/transaction/config/JtaTransactionManagerFactoryBean.java

@ -1,5 +1,5 @@ @@ -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<JtaTransact @@ -59,7 +59,7 @@ public class JtaTransactionManagerFactoryBean implements FactoryBean<JtaTransact
try {
Class<? extends JtaTransactionManager> clazz = (Class<? extends JtaTransactionManager>)
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);

21
spring-web-reactive/src/main/java/org/springframework/web/reactive/config/WebReactiveConfiguration.java

@ -13,6 +13,7 @@ @@ -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; @@ -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 { @@ -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 { @@ -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 { @@ -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<ViewResolver> resolvers = registry.getViewResolvers();
ViewResolutionResultHandler handler = new ViewResolutionResultHandler(resolvers, mvcConversionService());

12
spring-web/src/main/java/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.java

@ -615,7 +615,7 @@ public class Jackson2ObjectMapperBuilder { @@ -615,7 +615,7 @@ public class Jackson2ObjectMapperBuilder {
}
if (this.moduleClasses != null) {
for (Class<? extends Module> module : this.moduleClasses) {
objectMapper.registerModule(BeanUtils.instantiate(module));
objectMapper.registerModule(BeanUtils.instantiateClass(module));
}
}
@ -723,7 +723,7 @@ public class Jackson2ObjectMapperBuilder { @@ -723,7 +723,7 @@ public class Jackson2ObjectMapperBuilder {
try {
Class<? extends Module> jdk7Module = (Class<? extends Module>)
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 { @@ -732,7 +732,7 @@ public class Jackson2ObjectMapperBuilder {
try {
Class<? extends Module> jdk8Module = (Class<? extends Module>)
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 { @@ -743,7 +743,7 @@ public class Jackson2ObjectMapperBuilder {
try {
Class<? extends Module> javaTimeModule = (Class<? extends Module>)
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 { @@ -755,7 +755,7 @@ public class Jackson2ObjectMapperBuilder {
try {
Class<? extends Module> jodaModule = (Class<? extends Module>)
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 { @@ -767,7 +767,7 @@ public class Jackson2ObjectMapperBuilder {
try {
Class<? extends Module> kotlinModule = (Class<? extends Module>)
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

10
spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2CollectionHttpMessageConverter.java

@ -1,5 +1,5 @@ @@ -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; @@ -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<T extends Collection> @@ -185,12 +186,11 @@ public class Jaxb2CollectionHttpMessageConverter<T extends Collection>
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) {

6
spring-web/src/main/java/org/springframework/http/converter/xml/Jaxb2RootElementHttpMessageConverter.java

@ -1,5 +1,5 @@ @@ -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; @@ -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 @@ -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());

12
spring-web/src/main/java/org/springframework/http/converter/xml/SourceHttpMessageConverter.java

@ -45,7 +45,6 @@ import org.xml.sax.EntityResolver; @@ -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<T extends Source> extends AbstractHttpMe @@ -189,16 +188,17 @@ public class SourceHttpMessageConverter<T extends Source> 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);

4
spring-web/src/main/java/org/springframework/web/SpringServletContainerInitializer.java

@ -27,6 +27,7 @@ import javax.servlet.ServletException; @@ -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 @@ -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);

34
spring-web/src/main/java/org/springframework/web/util/WebUtils.java

@ -326,40 +326,6 @@ public abstract class WebUtils { @@ -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.

2
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java

@ -567,7 +567,7 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv @@ -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();

15
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/ServletWrappingController.java

@ -1,5 +1,5 @@ @@ -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; @@ -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; @@ -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<? extends Servlet> servletClass;
private String servletName;
@ -105,7 +104,7 @@ public class ServletWrappingController extends AbstractController @@ -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<? extends Servlet> servletClass) {
this.servletClass = servletClass;
}
@ -142,12 +141,12 @@ public class ServletWrappingController extends AbstractController @@ -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 @@ -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;

4
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.java

@ -612,9 +612,9 @@ public class MvcUriComponentsBuilder { @@ -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);
}

4
spring-webmvc/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java

@ -336,7 +336,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D @@ -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 @@ -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);

11
spring-webmvc/src/main/java/org/springframework/web/servlet/view/xslt/XsltView.java

@ -1,5 +1,5 @@ @@ -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; @@ -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; @@ -73,7 +74,7 @@ import org.springframework.web.util.WebUtils;
*/
public class XsltView extends AbstractUrlBasedView {
private Class<?> transformerFactoryClass;
private Class<? extends TransformerFactory> transformerFactoryClass;
private String sourceKey;
@ -97,7 +98,7 @@ public class XsltView extends AbstractUrlBasedView { @@ -97,7 +98,7 @@ public class XsltView extends AbstractUrlBasedView {
* <p>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<? extends TransformerFactory> transformerFactoryClass) {
Assert.isAssignable(TransformerFactory.class, transformerFactoryClass);
this.transformerFactoryClass = transformerFactoryClass;
}
@ -195,10 +196,10 @@ public class XsltView extends AbstractUrlBasedView { @@ -195,10 +196,10 @@ public class XsltView extends AbstractUrlBasedView {
* @see #setTransformerFactoryClass
* @see #getTransformerFactory()
*/
protected TransformerFactory newTransformerFactory(Class<?> transformerFactoryClass) {
protected TransformerFactory newTransformerFactory(Class<? extends TransformerFactory> 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");

4
spring-websocket/src/main/java/org/springframework/web/socket/handler/BeanCreatingHandlerProvider.java

@ -1,5 +1,5 @@ @@ -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<T> implements BeanFactoryAware { @@ -66,7 +66,7 @@ public class BeanCreatingHandlerProvider<T> implements BeanFactoryAware {
return this.beanFactory.createBean(this.handlerType);
}
else {
return BeanUtils.instantiate(this.handlerType);
return BeanUtils.instantiateClass(this.handlerType);
}
}

19
spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java

@ -35,6 +35,7 @@ import org.springframework.http.server.ServerHttpRequest; @@ -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 @@ -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 @@ -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(

Loading…
Cancel
Save