Example usage for java.lang Class getConstructors

List of usage examples for java.lang Class getConstructors

Introduction

In this page you can find the example usage for java.lang Class getConstructors.

Prototype

@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException 

Source Link

Document

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

Usage

From source file:com.bluecloud.ioc.classloader.ClassHandler.java

/**
 * <h3></h3> ?Class Instance
 * //from  w ww .  j ava2s . c om
 * @param className
 *            ??
 * @param index
 *            Class?constructorIndex?0Class?
 *            0
 * @param initargs
 *            ??
 * @return classNameClassObject
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 * @throws NoSuchMethodException
 * @throws SecurityException
 */
public static Object createObject(String className, int index, Object[] initargs)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException,
        InvocationTargetException, SecurityException, NoSuchMethodException {
    Class<?> clazz = (Class<?>) getClass(className, false);
    if (index < 0 || index > clazz.getConstructors().length - 1) {
        index = 0;
    }
    Constructor<?> constructor = clazz.getConstructors()[index];
    return constructor.newInstance(initargs);
}

From source file:org.lanternpowered.server.util.ReflectionHelper.java

@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(final Class<T> objectClass, @Nullable Object... args) {
    final Constructor<?>[] ctors = objectClass.getConstructors();
    if (args == null) {
        args = new Object[] { null };
    }//from ww  w .j  av a2 s.c  o  m
    // labeled loops
    dance: for (final Constructor<?> ctor : ctors) {
        final Class<?>[] paramTypes = ctor.getParameterTypes();
        if (paramTypes.length != args.length) {
            for (Object object : args) {
                if (object != null) { // hahahah
                    if (object.getClass().isArray()) {
                        final Object[] objects = deconstructArray(args).toArray();
                        return findConstructor(objectClass, objects);
                    }
                }
            }
            continue; // we haven't found the right constructor
        }
        for (int i = 0; i < paramTypes.length; i++) {
            final Class<?> parameter = paramTypes[i];
            if (!isAssignable(args[i] == null ? null : args[i].getClass(), parameter, true)) {
                continue dance; // continue the outer loop since we didn't find the right one
            }
        }
        // We've found the right constructor, now to actually construct it!
        return (Constructor<T>) ctor;
    }
    throw new IllegalArgumentException("Applicable constructor not found for class: "
            + objectClass.getCanonicalName() + " with args: " + Arrays.toString(args));
}

From source file:org.openvpms.web.component.im.view.IMObjectCollectionViewerFactory.java

/**
 * Returns a constructor to construct a new viewer.
 *
 * @param type       the Viewer type/*from  w w  w  . jav  a  2 s . c  o m*/
 * @param collection the collection property
 * @param object     the parent of the collection
 * @param context    the layout context. May be {@code null}
 * @return a constructor to construct the viewer, or {@code null} if none can be found
 */
private static Constructor getConstructor(Class type, CollectionProperty collection, IMObject object,
        LayoutContext context) {
    Constructor[] ctors = type.getConstructors();

    for (Constructor ctor : ctors) {
        // check parameters
        Class<?>[] ctorTypes = ctor.getParameterTypes();
        if (ctorTypes.length == 3) {
            Class<?> ctorCollection = ctorTypes[0];
            Class<?> ctorObj = ctorTypes[1];
            Class<?> ctorCtx = ctorTypes[2];

            if (ctorCollection.isAssignableFrom(collection.getClass())
                    && ctorObj.isAssignableFrom(object.getClass())
                    && ((context != null && ctorCtx.isAssignableFrom(context.getClass()))
                            || (context == null && LayoutContext.class.isAssignableFrom(ctorCtx)))) {
                return ctor;
            }
        }
    }
    return null;
}

From source file:com.linecorp.armeria.common.thrift.text.StructContext.java

private static boolean hasNoArgConstructor(Class clazz) {
    Constructor[] allConstructors = clazz.getConstructors();
    for (Constructor ctor : allConstructors) {
        Class<?>[] pType = ctor.getParameterTypes();
        if (pType.length == 0) {
            return true;
        }//from w  w  w.  j  a  v  a  2s. c om
    }

    return false;
}

From source file:org.jdto.impl.BeanClassUtils.java

/**
 * Check if the class has a default constructor.
 *
 * @param cls// w w w .j  a va 2  s  . c o  m
 * @return true if the type has default constructor, false if not.
 */
public static boolean hasDefaultConstructor(Class cls) {

    Constructor[] constructors = cls.getConstructors();

    //go through all the constructors trying to find one with no
    //parameters
    for (Constructor constructor : constructors) {
        if (constructor.getParameterTypes().length == 0) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.hadoop.hbase.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> Constructor<T> findConstructor(Class<T> type, Object... paramTypes) {
    Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
    for (Constructor<T> ctor : constructors) {
        Class<?>[] ctorParamTypes = ctor.getParameterTypes();
        if (ctorParamTypes.length != paramTypes.length) {
            continue;
        }/*from www.  j  av  a  2 s  . co m*/

        boolean match = true;
        for (int i = 0; i < ctorParamTypes.length && match; ++i) {
            Class<?> paramType = paramTypes[i].getClass();
            match = (!ctorParamTypes[i].isPrimitive()) ? ctorParamTypes[i].isAssignableFrom(paramType)
                    : ((int.class.equals(ctorParamTypes[i]) && Integer.class.equals(paramType))
                            || (long.class.equals(ctorParamTypes[i]) && Long.class.equals(paramType))
                            || (char.class.equals(ctorParamTypes[i]) && Character.class.equals(paramType))
                            || (short.class.equals(ctorParamTypes[i]) && Short.class.equals(paramType))
                            || (boolean.class.equals(ctorParamTypes[i]) && Boolean.class.equals(paramType))
                            || (byte.class.equals(ctorParamTypes[i]) && Byte.class.equals(paramType)));
        }

        if (match) {
            return ctor;
        }
    }
    throw new UnsupportedOperationException("Unable to find suitable constructor for class " + type.getName());
}

From source file:org.eclipse.wb.core.gef.MatchingEditPartFactory.java

private static EditPart createEditPart0(Object model, Class<?> modelClass, String partClassName) {
    try {/*  www  . j a  v  a  2 s  .com*/
        ClassLoader classLoader = modelClass.getClassLoader();
        Class<?> partClass = classLoader.loadClass(partClassName);
        // try all constructors
        for (Constructor<?> constructor : partClass.getConstructors()) {
            try {
                return (EditPart) constructor.newInstance(model);
            } catch (Throwable e) {
                // ignore
            }
        }
    } catch (Throwable e) {
        // ignore
    }
    return null;
}

From source file:io.konik.utils.RandomInvoiceGenerator.java

private static Constructor<?> findBiggestConstructor(Class<?> root) {
    Constructor<?>[] constructors = root.getConstructors();
    Constructor<?> biggestConstructor = null;
    for (Constructor<?> constructor : constructors) {
        if (biggestConstructor == null) {
            biggestConstructor = constructor;
            continue;
        }/*from  w  w  w.  ja v a2s.  c  om*/
        if (constructor.getTypeParameters().length > biggestConstructor.getParameterTypes().length) {
            biggestConstructor = constructor;
        }
    }
    return biggestConstructor;
}

From source file:org.pentaho.platform.util.versionchecker.PentahoVersionCheckReflectHelper.java

public static List performVersionCheck(final boolean ignoreExistingUpdates, final int versionRequestFlags) {
    // check to see if jar is loaded before continuing
    if (PentahoVersionCheckReflectHelper.isVersionCheckerAvailable()) {
        try {/*from www.  j a va  2s.c o  m*/

            // use reflection so anyone can delete the version checker jar without pain

            // PentahoVersionCheckHelper helper = new PentahoVersionCheckHelper();
            Class helperClass = Class
                    .forName("org.pentaho.platform.util.versionchecker.PentahoVersionCheckHelper"); //$NON-NLS-1$
            Object helper = helperClass.getConstructors()[0].newInstance(new Object[] {});

            // helper.setIgnoreExistingUpdates(ignoreExistingUpdates);
            Method setIgnoreExistingUpdatesMethod = helperClass.getDeclaredMethod("setIgnoreExistingUpdates", //$NON-NLS-1$
                    new Class[] { Boolean.TYPE });
            setIgnoreExistingUpdatesMethod.invoke(helper, new Object[] { new Boolean(ignoreExistingUpdates) });

            // helper.setVersionRequestFlags(versionRequestFlags);
            Method setVersionRequestFlagsMethod = helperClass.getDeclaredMethod("setVersionRequestFlags", //$NON-NLS-1$
                    new Class[] { Integer.TYPE });
            setVersionRequestFlagsMethod.invoke(helper, new Object[] { new Integer(versionRequestFlags) });

            // helper.performUpdate();
            Method performUpdateMethod = helperClass.getDeclaredMethod("performUpdate", new Class[] {}); //$NON-NLS-1$
            performUpdateMethod.invoke(helper, new Object[] {});

            // List results = helper.getResults();
            Method getResultsMethod = helperClass.getDeclaredMethod("getResults", new Class[] {}); //$NON-NLS-1$
            List results = (List) getResultsMethod.invoke(helper, new Object[] {});
            return results;

        } catch (Exception e) {
            // ignore errors
        }
    }

    return null;
}

From source file:org.openvpms.web.component.im.edit.IMObjectCollectionEditorFactory.java

/**
 * Returns a constructor to construct a new editor.
 *
 * @param type       the editor type//w w  w  . jav  a2  s .c o m
 * @param collection the collection property
 * @param object     the parent of the collection
 * @param context    the layout context. May be {@code null}
 * @return a constructor to construct the editor, or {@code null} if none can be found
 */
@SuppressWarnings("unchecked")
private static Constructor getConstructor(Class type, CollectionProperty collection, IMObject object,
        LayoutContext context) {
    Constructor[] ctors = type.getConstructors();

    for (Constructor ctor : ctors) {
        // check parameters
        Class[] ctorTypes = ctor.getParameterTypes();
        if (ctorTypes.length == 3) {
            Class ctorCollection = ctorTypes[0];
            Class ctorObj = ctorTypes[1];
            Class ctorLayout = ctorTypes[2];

            if (ctorCollection.isAssignableFrom(collection.getClass())
                    && ctorObj.isAssignableFrom(object.getClass())
                    && ((context != null && ctorLayout.isAssignableFrom(context.getClass()))
                            || (context == null && LayoutContext.class.isAssignableFrom(ctorLayout)))) {
                return ctor;
            }
        }
    }
    return null;
}