Find one parameter constructor which parameter is assignable from parameter class - Java Reflection

Java examples for Reflection:Constructor

Description

Find one parameter constructor which parameter is assignable from parameter class

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        Class parameter = String.class;
        System.out.println(findConstructor(clazz, parameter));
    }//from w  w  w.  j  ava2 s. co m

    /**
     * Find one parameter constructor which parameter is
     * assignable from parameter class
     *
     * @param clazz class whose constructor we are finding
     * @param parameter parameter class
     * @return constructor
     */
    public static <T> Constructor<T> findConstructor(Class<T> clazz,
            Class parameter) {
        Constructor[] constructors = clazz.getDeclaredConstructors();

        for (Constructor constructor : constructors) {
            if (constructor.getParameterTypes().length == 1
                    && constructor.getParameterTypes()[0]
                            .isAssignableFrom(parameter))
                return constructor;
        }

        return null;
    }

    /**
     * Find constructor of class which has these parameters
     *
     * @param clazz class of constructor we are finding
     * @param parameters constructor parameters
     * @param <T> type of class
     * @return constructor or null if cannot be find
     */
    public static <T> Constructor<T> findConstructor(Class<T> clazz,
            Class[] parameters) {
        Constructor[] constructors = clazz.getConstructors();

        for (Constructor constructor : constructors) {
            if (constructor.getParameterTypes().length == parameters.length) {
                if (isAssignable(constructor.getParameterTypes(),
                        parameters))
                    return constructor;
            }
        }

        return null;
    }

    /**
     * Determine if classes can be assigned from
     *
     * @param c1 first array of classes
     * @param c2 second array of classes
     * @return true if c1 array can be assigned from c2 array
     */
    public static boolean isAssignable(Class[] c1, Class[] c2) {
        if (c1 == null || c2 == null)
            return false;

        if (c1.length != c2.length)
            return false;

        for (int i = 0; i < c1.length; i++) {
            if (!c1[i].isAssignableFrom(c2[i]))
                return false;
        }

        return true;
    }
}

Related Tutorials