Example usage for org.apache.commons.beanutils ConstructorUtils getAccessibleConstructor

List of usage examples for org.apache.commons.beanutils ConstructorUtils getAccessibleConstructor

Introduction

In this page you can find the example usage for org.apache.commons.beanutils ConstructorUtils getAccessibleConstructor.

Prototype

public static Constructor getAccessibleConstructor(Constructor ctor) 

Source Link

Document

Returns accessible version of the given constructor.

Usage

From source file:org.apache.empire.db.DBReader.java

/**
 * copied from org.apache.commons.beanutils.ConstructorUtils since it's private there
 *///from   w  w w .j  a v  a 2 s.c o m
@SuppressWarnings("unchecked")
private static Constructor findMatchingAccessibleConstructor(Class clazz, Class[] parameterTypes) {
    // See if we can find the method directly
    // probably faster if it works
    // (I am not sure whether it's a good idea to run into Exceptions)
    // try {
    //     Constructor ctor = clazz.getConstructor(parameterTypes);
    //     try {
    //         // see comment in org.apache.commons.beanutils.ConstructorUtils
    //         ctor.setAccessible(true);
    //     } catch (SecurityException se) { /* ignore */ }
    //     return ctor;
    // } catch (NoSuchMethodException e) { /* SWALLOW */ }

    // search through all constructors 
    int paramSize = parameterTypes.length;
    Constructor[] ctors = clazz.getConstructors();
    for (int i = 0, size = ctors.length; i < size; i++) { // compare parameters
        Class[] ctorParams = ctors[i].getParameterTypes();
        int ctorParamSize = ctorParams.length;
        if (ctorParamSize == paramSize) { // Param Size matches
            boolean match = true;
            for (int n = 0; n < ctorParamSize; n++) {
                if (!ObjectUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) {
                    match = false;
                    break;
                }
            }
            if (match) {
                // get accessible version of method
                Constructor ctor = ConstructorUtils.getAccessibleConstructor(ctors[i]);
                if (ctor != null) {
                    try {
                        ctor.setAccessible(true);
                    } catch (SecurityException se) {
                        /* ignore */ }
                    return ctor;
                }
            }
        }
    }
    return null;
}