Example usage for java.lang Class getDeclaredConstructors

List of usage examples for java.lang Class getDeclaredConstructors

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @param signature/*from   ww w .  j a v a  2s .c om*/
 *            the signature of method in same format as {@link #getConstructorSignature(Constructor)}.
 * 
 * @return the {@link Constructor} for given signature. This constructor can have any visibility, i.e. we
 *         can find even protected/private constructors.
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructorBySignature(Class<T> clazz, String signature) throws Exception {
    Assert.isNotNull(clazz);
    Assert.isNotNull(signature);
    // check all declared constructors
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (getConstructorSignature(constructor).equals(signature)) {
            constructor.setAccessible(true);
            return (Constructor<T>) constructor;
        }
    }
    // not found
    return null;
}

From source file:com.github.juanmf.java2plant.Parser.java

protected static void addUses(Set<Relation> relations, Class<?> fromType) {
    Method[] methods = fromType.getDeclaredMethods();
    for (Method m : methods) {
        if (!Modifier.isPrivate(m.getModifiers())) {
            addMethodUses(relations, fromType, m);
        }/*from w  w w.  j  a  va  2 s. c om*/
    }
    Constructor<?>[] constructors = fromType.getDeclaredConstructors();
    for (Constructor<?> c : constructors) {
        if (!Modifier.isPrivate(c.getModifiers())) {
            addConstructorUses(relations, fromType, c);
        }
    }
}

From source file:org.grouplens.grapht.util.Types.java

/**
 * Return true if the type is not abstract and not an interface, and has
 * a constructor annotated with {@link Inject} or its only constructor
 * is the default constructor.//from w ww  .j a  v  a2s .co  m
 * 
 * @param type A class type
 * @return True if the class type is instantiable
 */
public static boolean isInstantiable(Class<?> type) {
    if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()) {
        // first check for a constructor annotated with @Inject, 
        //  - this doesn't care how many we'll let the injector complain
        //    if there are more than one
        for (Constructor<?> c : type.getDeclaredConstructors()) {
            if (c.getAnnotation(Inject.class) != null) {
                return true;
            }
        }

        // check if we only have the public default constructor
        if (type.getConstructors().length == 1 && type.getConstructors()[0].getParameterTypes().length == 0) {
            return true;
        }
    }

    // no constructor available
    return false;
}

From source file:com.dianping.squirrel.client.util.ClassUtils.java

@SuppressWarnings("unchecked")
private static <T> Constructor<T> getMatchingDeclaredConstructor(Class<T> clazz, Class<?>[] parameterTypes) {
    try {//w  ww.jav a 2s  .c  o m
        Constructor<T> ctor = clazz.getConstructor(parameterTypes);
        try {
            ctor.setAccessible(true);
        } catch (SecurityException se) {
            // do nothing
        }
        return ctor;

    } catch (NoSuchMethodException e) {
    }

    int paramSize = parameterTypes.length;
    Constructor<?>[] ctors = clazz.getDeclaredConstructors();
    for (int i = 0, size = ctors.length; i < size; i++) {
        Class<?>[] ctorParams = ctors[i].getParameterTypes();
        int ctorParamSize = ctorParams.length;
        if (ctorParamSize == paramSize) {
            boolean match = true;
            for (int n = 0; n < ctorParamSize; n++) {
                if (!MethodUtils.isAssignmentCompatible(ctorParams[n], parameterTypes[n])) {
                    match = false;
                    break;
                }
            }

            if (match) {
                Constructor<?> ctor = getDeclaredConstructor(ctors[i]);
                if (ctor != null) {
                    return (Constructor<T>) ctor;
                }
            }
        }
    }
    return null;
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

private static Constructor<?> getConstructor(Class<?> clazz) {
    Constructor<?> res;/* w ww .  j av a2  s. com*/
    Constructor<?>[] constructors = clazz.getDeclaredConstructors();
    if (constructors.length == 0) {
        throw new ITestInitializationException(clazz, null);
    }
    res = constructors[0];
    for (int i = 1; i < constructors.length; i++) {
        if (constructors[i].getParameterTypes().length == 0) {
            res = constructors[i];
            break;
        }
    }
    try {
        res.setAccessible(true);
    } catch (SecurityException e) {
        throw new ITestInitializationException(clazz, e);
    }
    return res;
}

From source file:org.batoo.common.reflect.ReflectHelper.java

private static ConstructorAccessor createConstructorImpl(Constructor<?> constructor) {
    try {/*from   www .  j a v  a 2s. co  m*/
        final Class<?> magClass = Class.forName("sun.reflect.MethodAccessorGenerator");
        final Constructor<?> c = magClass.getDeclaredConstructors()[0];
        final Method generateMethod = magClass.getMethod("generateConstructor", Class.class, Class[].class,
                Class[].class, Integer.TYPE);

        ReflectHelper.setAccessible(c, true);
        ReflectHelper.setAccessible(generateMethod, true);

        try {
            final Object mag = c.newInstance();

            return new SunConstructorAccessor(
                    generateMethod.invoke(mag, constructor.getDeclaringClass(), constructor.getParameterTypes(),
                            constructor.getExceptionTypes(), constructor.getModifiers()));
        } finally {
            ReflectHelper.setAccessible(c, false);
            ReflectHelper.setAccessible(generateMethod, false);
        }
    } catch (final Exception e) {
        throw new RuntimeException("Constructor generation failed", e);
    }
}

From source file:org.jgentleframework.utils.Utils.java

/**
 * Returns the default {@link Constructor} of the given class. The default
 * constructor is identified with annotated {@link DefaultConstructor}
 * annotation.//  w  ww  .  j a  v  a2 s.  com
 * 
 * @param clazz
 *            the given class
 * @return returns the default constructor if it exists, if not, return
 *         <code>null</code>.
 * @throws InOutDependencyException
 *             throws this exception if there are more than one default
 *             constructor.
 * @see DefaultConstructor
 */
public static Constructor<?> getDefaultConstructor(Class<?> clazz) {

    Constructor<?> constructor = null;
    int i = 0;
    for (Constructor<?> objCons : clazz.getDeclaredConstructors()) {
        if (objCons.isAnnotationPresent(DefaultConstructor.class)) {
            constructor = objCons;
            i++;
        }
    }
    if (i > 1) {
        throw new RuntimeException("There are more than one default constructor.");
    }
    return constructor;
}

From source file:com.impetus.kundera.utils.KunderaCoreUtils.java

/**
 * @param clazz/*from w  ww  .j  ava 2 s .  c o  m*/
 * @return
 */
public static Object createNewInstance(Class clazz) {
    Object target = null;
    try {
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            if ((Modifier.isProtected(constructor.getModifiers())
                    || Modifier.isPublic(constructor.getModifiers()))
                    && constructor.getParameterTypes().length == 0) {
                constructor.setAccessible(true);
                target = constructor.newInstance();
                constructor.setAccessible(false);
                break;
            }
        }
        return target;

    } catch (InstantiationException iex) {
        logger.error("Error while creating an instance of {} .", clazz);
        throw new PersistenceException(iex);
    }

    catch (IllegalAccessException iaex) {
        logger.error("Illegal Access while reading data from {}, Caused by: .", clazz, iaex);
        throw new PersistenceException(iaex);
    }

    catch (Exception e) {
        logger.error("Error while creating an instance of {}, Caused by: .", clazz, e);
        throw new PersistenceException(e);
    }
}

From source file:org.apache.openaz.xacml.util.FactoryFinder.java

public static <T> T newInstance(String className, Class<T> classExtends, ClassLoader cl, boolean doFallback,
        Properties xacmlProperties) throws FactoryException {
    try {/*from w  w w  .j a  v a 2 s  . c  om*/
        Class<?> providerClass = getProviderClass(className, cl, doFallback);
        if (classExtends.isAssignableFrom(providerClass)) {
            Object instance = null;
            if (xacmlProperties == null) {
                instance = providerClass.newInstance();
            } else {
                //
                // Search for a constructor that takes Properties
                //
                for (Constructor<?> constructor : providerClass.getDeclaredConstructors()) {
                    Class<?>[] params = constructor.getParameterTypes();
                    if (params.length == 1 && params[0].isAssignableFrom(Properties.class)) {
                        instance = constructor.newInstance(xacmlProperties);
                    }
                }
                if (instance == null) {
                    logger.warn("No constructor that takes a Properties object.");
                    instance = providerClass.newInstance();
                }
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Created new instance of " + providerClass + " using ClassLoader: " + cl);
            }
            return classExtends.cast(instance);
        } else {
            throw new ClassNotFoundException(
                    "Provider " + className + " does not extend " + classExtends.getCanonicalName());
        }
    } catch (ClassNotFoundException ex) {
        throw new FactoryException("Provider " + className + " not found", ex);
    } catch (Exception ex) {
        throw new FactoryException("Provider " + className + " could not be instantiated: " + ex.getMessage(),
                ex);
    }
}

From source file:org.paxml.util.ReflectUtils.java

/**
 * Construct object from class using the default constructor.
 * /*from  ww  w.ja v  a  2  s .com*/
 * @param <T>
 *            the class type
 * @param clazz
 *            the class
 * @param constructParams
 *            the parameters to call constructor with
 * @return the object
 * @throws RuntimeException
 *             if the construction fails.
 */
public static <T> T createObject(Class<? extends T> clazz, Object... constructParams) {
    Constructor<T> con = null;
    Class[] argTypes = null;
    for (Constructor c : clazz.getDeclaredConstructors()) {
        argTypes = c.getParameterTypes();
        if (argTypes.length == constructParams.length) {
            con = c;
            break;
        }
    }
    if (con == null) {
        throw new PaxmlRuntimeException("No constructor found with " + constructParams.length + " parameters!");
    }
    try {
        Object[] args = new Object[constructParams.length];
        for (int i = args.length - 1; i >= 0; i--) {
            args[i] = coerceType(constructParams[i], argTypes[i]);
        }
        con.setAccessible(true);
        return con.newInstance(args);
    } catch (Exception e) {
        throw new PaxmlRuntimeException("Cannot create instance from class: " + clazz.getName(), e);
    }
}