org.sfm.reflect.ReflectionConstructorDefinitionFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simpleFlatMapper Show documentation
Show all versions of simpleFlatMapper Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
package org.sfm.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
public class ReflectionConstructorDefinitionFactory {
@SuppressWarnings("unchecked")
public static List> extractConstructors(Type target) {
Class clazz = TypeHelper.toClass(target);
List> constructorDefinitions = new ArrayList>();
for(Constructor> constructor : clazz.getDeclaredConstructors()) {
ConstructorDefinition definition = new ConstructorDefinition(constructor, getConstructorParameters(constructor, target));
constructorDefinitions.add(definition);
}
return constructorDefinitions;
}
private static ConstructorParameter[] getConstructorParameters(Constructor> constructor, Type target) {
ConstructorParameter[] parameters = new ConstructorParameter[constructor.getParameterTypes().length];
TypeVariable>[] typeParameters = TypeHelper.toClass(target).getTypeParameters();
for(int i = 0; i < parameters.length; i++) {
String name = getName(i, constructor);
Type paramType = constructor.getGenericParameterTypes()[i];
Type resolvedParamType = null;
if (paramType instanceof TypeVariable) {
TypeVariable> tv = (TypeVariable>) paramType;
paramType = constructor.getParameterTypes()[i];
ParameterizedType pt = (ParameterizedType) target;
for (TypeVariable> typeParameter : typeParameters) {
if (typeParameter.getName().equals(tv.getName())) {
resolvedParamType = pt.getActualTypeArguments()[i];
break;
}
}
}
if (resolvedParamType == null) {
resolvedParamType = paramType;
}
parameters[i] = new ConstructorParameter(name, paramType, resolvedParamType);
}
return parameters;
}
private static String getName(int i, Constructor> constructor) {
return "arg" + i;
}
}