find Proper Constructor by parameter types via reflection - Java Reflection

Java examples for Reflection:Constructor

Description

find Proper Constructor by parameter types via reflection

Demo Code


//package com.java2s;
import java.lang.reflect.Constructor;

import java.util.List;

public class Main {


    public static Constructor<?> findProperConstructor(Class<?> clazz,
            List<Class<?>> types) {
        Constructor<?>[] constructors = clazz.getConstructors();

        for (Constructor<?> constructor : constructors) {
            if (isProperConstructor(constructor, types)) {
                return constructor;
            }//  w  w w. j av a2s  .  com
        }

        return null;
    }

    protected static boolean isProperConstructor(
            Constructor<?> constructor, List<Class<?>> types) {
        Class<?>[] constructorParams = constructor.getParameterTypes();

        if (constructorParams.length != types.size()) {
            return false;
        }

        for (int i = 0; i < types.size(); ++i) {
            if (!constructorParams[i].isAssignableFrom(types.get(i))) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials