Initialize ConstructorExpression eagerly

This commit is contained in:
Timo Westkämper 2016-07-16 09:49:04 +03:00
parent 1a1b7f42d6
commit 64a05e7b1f

View File

@ -20,7 +20,6 @@ import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import com.google.common.base.Function;
@ -62,10 +61,9 @@ public class ConstructorExpression<T> extends FactoryExpressionBase<T> {
private final Class<?>[] parameterTypes;
@Nullable
private transient Constructor<?> constructor;
private final transient Constructor<?> constructor;
private transient Iterable<Function<Object[], Object[]>> transformers;
private final transient Iterable<Function<Object[], Object[]>> transformers;
protected ConstructorExpression(Class<? extends T> type, Expression<?>... args) {
this(type, getParameterTypes(args), ImmutableList.copyOf(args));
@ -77,8 +75,14 @@ public class ConstructorExpression<T> extends FactoryExpressionBase<T> {
protected ConstructorExpression(Class<? extends T> type, Class<?>[] paramTypes, ImmutableList<Expression<?>> args) {
super(type);
this.parameterTypes = getConstructorParameters(type, paramTypes).clone();
this.args = args;
try {
this.parameterTypes = getConstructorParameters(type, paramTypes).clone();
this.args = args;
this.constructor = getConstructor(getType(), parameterTypes);
this.transformers = getTransformers(constructor);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
}
/**
@ -128,18 +132,12 @@ public class ConstructorExpression<T> extends FactoryExpressionBase<T> {
@SuppressWarnings("unchecked")
public T newInstance(Object... args) {
try {
if (constructor == null) {
constructor = getConstructor(getType(), parameterTypes);
transformers = getTransformers(constructor);
}
for (Function<Object[], Object[]> transformer : transformers) {
args = transformer.apply(args);
}
return (T) constructor.newInstance(args);
} catch (SecurityException e) {
throw new ExpressionException(e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new ExpressionException(e.getMessage(), e);
} catch (InstantiationException e) {
throw new ExpressionException(e.getMessage(), e);
} catch (IllegalAccessException e) {