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

Issue: SPR-14486
This commit is contained in:
Juergen Hoeller
2016-07-19 19:21:06 +02:00
parent b3253ca5e2
commit aaac199e8b
54 changed files with 285 additions and 242 deletions

View File

@@ -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());
}
}

View File

@@ -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;
}
}

View File

@@ -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, " +

View File

@@ -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 '" +

View File

@@ -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);
}
}

View File

@@ -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 {
/**
* 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 {
/**
* 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 {
/**
* 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");

View File

@@ -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);
}
}

View File

@@ -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<Object>) requiredType.newInstance();
convertedCopy = (Collection<Object>)
ReflectionUtils.accessibleConstructor(requiredType).newInstance();
}
}
catch (Throwable ex) {
@@ -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) {

View File

@@ -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 {

View File

@@ -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);
}
}

View File

@@ -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<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) {

View File

@@ -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<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) {

View File

@@ -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();
}
/**

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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 {

View File

@@ -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;
}

View File

@@ -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(

View File

@@ -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 {

View File

@@ -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());
}
}

View File

@@ -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;

View File

@@ -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);

View File

@@ -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<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 {
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);
}
}

View File

@@ -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());
}
}
}

View File

@@ -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);
}
}

View File

@@ -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 {
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 {
@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());
}
}
}

View File

@@ -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");

View File

@@ -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

View File

@@ -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);
}
}

View File

@@ -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());
}

View File

@@ -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<? 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);

View File

@@ -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> {
@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);

View File

@@ -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<? 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);
}
}

View File

@@ -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() {

View File

@@ -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";

View File

@@ -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()) {

View File

@@ -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);
}
}
}

View File

@@ -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()) {

View File

@@ -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> 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

View File

@@ -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
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);

View File

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

View File

@@ -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 {
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 {
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 {
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 {
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 {
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

View File

@@ -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<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) {

View File

@@ -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());

View File

@@ -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
}
}
@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);

View File

@@ -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);

View File

@@ -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.

View File

@@ -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();

View File

@@ -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<? extends Servlet> 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<? extends Servlet> 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;

View File

@@ -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);
}

View File

@@ -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);

View File

@@ -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<? extends TransformerFactory> transformerFactoryClass;
private String sourceKey;
@@ -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 {
* @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");

View File

@@ -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 {
return this.beanFactory.createBean(this.handlerType);
}
else {
return BeanUtils.instantiate(this.handlerType);
return BeanUtils.instantiateClass(this.handlerType);
}
}

View File

@@ -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(