All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sfm.reflect.ReflectionConstructorDefinitionFactory Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

There is a newer version: 1.10.3
Show newest version
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;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy