Java Reflection Constructor Get getConstructor(final Class theClass, final Class... parameterTypes)

Here you can find the source of getConstructor(final Class theClass, final Class... parameterTypes)

Description

Returns class constructor for the specified argument types.

License

Open Source License

Parameter

Parameter Description
theClass class to process
parameterTypes constructor argument types

Exception

Parameter Description
NoSuchMethodException an exception

Return

class constructor for the specified argument types

Declaration

public static Constructor getConstructor(final Class theClass, final Class... parameterTypes)
        throws NoSuchMethodException 

Method Source Code

//package com.java2s;
/*/* w  w w .  j a v  a 2  s . co m*/
 * This file is part of WebLookAndFeel library.
 *
 * WebLookAndFeel library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * WebLookAndFeel library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with WebLookAndFeel library.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.*;

public class Main {
    /**
     * Returns class constructor for the specified argument types.
     *
     * @param theClass       class to process
     * @param parameterTypes constructor argument types
     * @return class constructor for the specified argument types
     * @throws NoSuchMethodException
     */
    public static Constructor getConstructor(final Class theClass, final Class... parameterTypes)
            throws NoSuchMethodException {
        // todo Constructors priority check (by super types)
        // todo For now some constructor with [Object] arg might be used instead of constructor with [String]
        // todo To avoid issues don't call constructors with same amount of arguments and which are castable to each other
        if (parameterTypes.length == 0) {
            return theClass.getConstructor();
        } else {
            // Constructors can be used only from the topmost class so we don't need to look for them in superclasses
            for (final Constructor constructor : theClass.getDeclaredConstructors()) {
                final Class[] types = constructor.getParameterTypes();

                // Inappropriate constructor
                if (types.length != parameterTypes.length) {
                    continue;
                }

                // Constructor with no parameters
                if (types.length == parameterTypes.length && types.length == 0) {
                    return constructor;
                }

                // Checking types
                boolean fits = true;
                for (int i = 0; i < types.length; i++) {
                    if (!isAssignable(types[i], parameterTypes[i])) {
                        fits = false;
                        break;
                    }
                }
                if (fits) {
                    return constructor;
                }
            }

            // Throwing proper exception that constructor was not found
            throw new NoSuchMethodException(theClass.getCanonicalName() + argumentTypesToString(parameterTypes));
        }
    }

    /**
     * Returns whether first type is assignable from second one or not.
     *
     * @param type checked whether is assignable, always not null
     * @param from checked type, might be null
     * @return true if first type is assignable from second one, false otherwise
     */
    public static boolean isAssignable(final Class type, final Class from) {
        if (from == null) {
            return !type.isPrimitive();
        } else if (type.isAssignableFrom(from)) {
            return true;
        } else if (type.isPrimitive()) {
            if (type == boolean.class) {
                return Boolean.class.isAssignableFrom(from);
            } else if (type == int.class) {
                return Integer.class.isAssignableFrom(from);
            } else if (type == char.class) {
                return Character.class.isAssignableFrom(from);
            } else if (type == byte.class) {
                return Byte.class.isAssignableFrom(from);
            } else if (type == short.class) {
                return Short.class.isAssignableFrom(from);
            } else if (type == long.class) {
                return Long.class.isAssignableFrom(from);
            } else if (type == float.class) {
                return Float.class.isAssignableFrom(from);
            } else if (type == double.class) {
                return Double.class.isAssignableFrom(from);
            } else if (type == void.class) {
                return Void.class.isAssignableFrom(from);
            }
        }
        return false;
    }

    /**
     * Returns text representation for array of argument types.
     *
     * @param argTypes argument types
     * @return text representation for array of argument types
     */
    private static String argumentTypesToString(final Class[] argTypes) {
        final StringBuilder buf = new StringBuilder("(");
        if (argTypes != null) {
            for (int i = 0; i < argTypes.length; i++) {
                if (i > 0) {
                    buf.append(", ");
                }
                final Class c = argTypes[i];
                buf.append((c == null) ? "null" : c.getCanonicalName());
            }
        }
        return buf.append(")").toString();
    }
}

Related

  1. getConstructor(Class cls, Object... args)
  2. getConstructor(Class instanceType)
  3. getConstructor(Class targetClass, Class... parameterTypes)
  4. getConstructor(Class type, Class... parameterTypes)
  5. getConstructor(Class type, Class[] parameterTypes)
  6. getConstructor(final Class clazz, final Class... parameterTypes)
  7. getConstructor(final Class clazz, final Class[] paramTypes)
  8. getConstructor(final Class valueClass, final Class parameter)
  9. getConstructor(final Class clazz, final Class... parametertypes)