com.tngtech.configbuilder.util.ConstructionHelper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of config-builder Show documentation
Show all versions of config-builder Show documentation
The Config Builder creates fully configured instances of config classes, using values from various sources like properties files, command line arguments etc.
package com.tngtech.configbuilder.util;
import com.tngtech.configbuilder.configuration.ErrorMessageSetup;
import com.tngtech.configbuilder.exception.ConfigBuilderException;
import com.tngtech.configbuilder.exception.NoConstructorFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ConstructionHelper {
private final static Logger log = LoggerFactory.getLogger(ConstructionHelper.class);
private ErrorMessageSetup errorMessageSetup;
public ConstructionHelper(ConfigBuilderFactory configBuilderFactory) {
this.errorMessageSetup = configBuilderFactory.getInstance(ErrorMessageSetup.class);
}
public T getInstance(Class configClass, Object... objects) {
try {
Constructor tConstructor = findSuitableConstructor(configClass, objects);
log.debug("found constructor - instantiating {}", configClass.getName());
tConstructor.setAccessible(true);
return tConstructor.newInstance(objects);
} catch (InstantiationException e) {
throw createConfigBuilderException(e);
} catch (IllegalAccessException e) {
throw createConfigBuilderException(e);
} catch (InvocationTargetException e) {
throw createConfigBuilderException(e);
}
}
private ConfigBuilderException createConfigBuilderException(Exception e) {
return new ConfigBuilderException(errorMessageSetup.getErrorMessage(e), e);
}
@SuppressWarnings("unchecked")
private Constructor findSuitableConstructor(Class configClass, Object... objects) {
log.debug("trying to find a constructor for {} matching the arguments of build()", configClass.getName());
Constructor[] constructors = configClass.getDeclaredConstructors();
for (Constructor constructor : constructors) {
if (constructorIsMatching(constructor, objects)) {
return constructor;
}
}
throw new NoConstructorFoundException(errorMessageSetup.getErrorMessage(NoConstructorFoundException.class));
}
private boolean constructorIsMatching(Constructor constructor, Object... objects) {
Class>[] parameterTypes = constructor.getParameterTypes();
if (parameterTypes.length != objects.length) {
return false;
} else {
boolean constructorIsMatching = true;
for (int i = 0; i < parameterTypes.length; i++) {
constructorIsMatching &= parameterTypes[i].isAssignableFrom(objects[i].getClass());
}
return constructorIsMatching;
}
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy