Java Reflection Constructor Get getConstructorWithArgs(Class clazz, Object... args)

Here you can find the source of getConstructorWithArgs(Class clazz, Object... args)

Description

Looks for a constructor matching the argument given.

License

Open Source License

Parameter

Parameter Description
clazz - class to look for the constructor in
args - arguments that the constructor should have

Return

first match found

Declaration

public static <e extends Object> Constructor<e> getConstructorWithArgs(Class<e> clazz, Object... args) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Constructor;

public class Main {
    /**/*  w w w  .  ja v a2  s.  com*/
     * Looks for a constructor matching the argument given.
     *
     * @param clazz - class to look for the constructor in
     * @param args  - arguments that the constructor should have
     * @return first match found
     */
    public static <e extends Object> Constructor<e> getConstructorWithArgs(Class<e> clazz, Object... args) {
        if (clazz != null) {
            Constructor<?>[] constructors = clazz.getConstructors();
            for (Constructor<?> constructor : constructors) {
                if (constructor.getParameterTypes().length == args.length) {
                    Class<?>[] pType = constructor.getParameterTypes();
                    for (int i = 0; i < pType.length; i++) {
                        if (!pType[i].equals(args[i].getClass())) {
                            continue;
                        }
                        if (i == pType.length - 1) {
                            try {
                                Constructor<e> con = (Constructor<e>) constructor;
                                return con;
                            } catch (ClassCastException e) {

                            }
                        }
                    }
                }
            }
        }
        return null;
    }
}

Related

  1. getConstructors(final Class cl, final int params)
  2. getConstructorSignature(final Constructor constructor)
  3. getConstructorSignatureWithLongTypeNames(Constructor init)
  4. getConstructorSimpleName(Constructor constructor)
  5. getConstructorsOfLength(final Class clazz, final int length)
  6. getConstructorWithLeastParametersFromList( ArrayList constructorsFromType)
  7. getConstructorWithNoParams(Class clazz)
  8. getConstructorWithReflection(String className, Class... parameterTypes)