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:io.coala.factory.ClassUtil.java

/**
 * @param returnType the type of the stored property value
 * @param args the arguments for construction
 * @return the property value's class instantiated
 * @throws CoalaException if the property's value is no instance of
 *             valueClass/*w w  w  .ja  v  a  2  s. c  om*/
 */
@SuppressWarnings("unchecked")
public static <T> T instantiate(final Class<T> returnType, final Object... args) throws CoalaException {
    if (returnType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.create("returnType");

    final Class<?>[] argTypes = new Class<?>[args.length];
    for (int i = 0; i < args.length; i++)
        argTypes[i] = args[i] == null ? null : args[i].getClass();

    for (Constructor<?> constructor : returnType.getConstructors()) {
        final Class<?>[] paramTypes = constructor.getParameterTypes();
        if (paramTypes.length != args.length) // different argument count,
        // try next constructor
        {
            continue;
        }

        boolean match = true;
        for (int i = 0; match && i < paramTypes.length; i++) {
            if (args[i] == null && !paramTypes[i].isPrimitive())
                argTypes[i] = paramTypes[i];
            else if (!isAssignableFrom(paramTypes[i], argTypes[i]))
                match = false;
        }

        if (!match) // no matching parameter types, try next constructor
        {
            continue;
        }

        try {
            return (T) constructor.newInstance(args);
        } catch (final InvocationTargetException exception) {
            // exception caused by the constructor itself, pass cause thru
            throw exception.getCause() instanceof CoalaException ? (CoalaException) exception.getCause()
                    : CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType,
                            Arrays.asList(argTypes));
        } catch (final Exception exception) {
            throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType, Arrays.asList(argTypes));
        }
    }
    throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(returnType, Arrays.asList(argTypes));
}

From source file:com.velonuboso.made.core.common.Helper.java

/**
 * Modification by rhgarcia from the implementation of M. Jessup 
 * at StackOverflow.//from   w  w  w.  ja  va2 s  . com
 * http://stackoverflow.com/users/294738/m-jessup
 */
public static ArrayList<Class> topologicalOrder(ArrayList<Class> classes) throws Exception {

    Node[] allNodes = new Node[classes.size()];
    HashMap<String, Node> nodes = new HashMap<String, Node>();

    for (int i = 0; i < classes.size(); i++) {
        Class c = classes.get(i);
        Node n = new Node(c);
        allNodes[i] = n;
        nodes.put(c.getSimpleName(), n);
    }

    for (int i = 0; i < allNodes.length; i++) {
        Node n = allNodes[i];
        Class c = n.getC();
        Archetype a = (Archetype) c.getConstructors()[0].newInstance();
        ArrayList<Class> dependencies = a.getDependencies();
        for (int j = 0; j < dependencies.size(); j++) {
            Class dep = dependencies.get(j);
            Node nAux = nodes.get(dep.getSimpleName());
            if (nAux != null) {
                nAux.addEdge(n);
            }
        }
    }

    //L <- Empty list that will contain the sorted elements
    ArrayList<Node> L = new ArrayList<Node>();

    //S <- Set of all nodes with no incoming edges
    HashSet<Node> S = new HashSet<Node>();
    for (Node n : allNodes) {
        if (n.inEdges.size() == 0) {
            S.add(n);
        }
    }

    //while S is non-empty do
    while (!S.isEmpty()) {
        //remove a node n from S
        Node n = S.iterator().next();
        S.remove(n);

        //insert n into L
        L.add(n);

        //for each node m with an edge e from n to m do
        for (Iterator<Edge> it = n.outEdges.iterator(); it.hasNext();) {
            //remove edge e from the graph
            Edge e = it.next();
            Node m = e.to;
            it.remove();//Remove edge from n
            m.inEdges.remove(e);//Remove edge from m

            //if m has no other incoming edges then insert m into S
            if (m.inEdges.isEmpty()) {
                S.add(m);
            }
        }
    }
    //Check to see if all edges are removed
    boolean cycle = false;
    for (Node n : allNodes) {
        if (!n.inEdges.isEmpty()) {
            cycle = true;
            break;
        }
    }
    if (cycle) {
        throw new Exception("Cycle present, topological sort not possible");
    }
    System.out.println("Topological Sort: " + Arrays.toString(L.toArray()));

    ArrayList<Class> ret = new ArrayList<Class>();
    for (Node n : L) {
        ret.add(n.getC());
    }
    return ret;
}

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.// ww w  . j av a  2 s.com
 * 
 * @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:org.mule.util.ClassUtils.java

/**
 *  Returns available constructor in the target class that as the parameters specified.
 *
 * @param clazz the class to search//  ww w  .  j  a  v  a 2s  . co  m
 * @param paramTypes the param types to match against
 * @param exactMatch should exact types be used (i.e. equals rather than isAssignableFrom.)
 * @return The matching constructor or null if no matching constructor is found
 */
public static Constructor getConstructor(Class clazz, Class[] paramTypes, boolean exactMatch) {
    Constructor[] ctors = clazz.getConstructors();
    for (int i = 0; i < ctors.length; i++) {
        Class[] types = ctors[i].getParameterTypes();
        if (types.length == paramTypes.length) {
            int matchCount = 0;
            for (int x = 0; x < types.length; x++) {
                if (paramTypes[x] == null) {
                    matchCount++;
                } else {
                    if (exactMatch) {
                        if (paramTypes[x].equals(types[x]) || types[x].equals(paramTypes[x])) {
                            matchCount++;
                        }
                    } else {
                        if (paramTypes[x].isAssignableFrom(types[x])
                                || types[x].isAssignableFrom(paramTypes[x])) {
                            matchCount++;
                        }
                    }
                }
            }
            if (matchCount == types.length) {
                return ctors[i];
            }
        }
    }
    return null;
}

From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java

static List<ActionParameterType> findConstructorInfo(final Class<?> beanType) {
    List<ActionParameterType> parametersInfo = new ArrayList<ActionParameterType>();
    Constructor<?>[] constructors = beanType.getConstructors();
    // find default ctor
    Constructor<?> constructor = PropertyUtils.findDefaultCtor(constructors);
    // find ctor with JsonCreator ann
    if (constructor == null) {
        constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
    }// www  . ja  va  2 s . c  o m
    if (constructor != null) {
        int parameterCount = constructor.getParameterTypes().length;

        if (parameterCount > 0) {
            Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

            Class<?>[] parameters = constructor.getParameterTypes();
            int paramIndex = 0;
            for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                for (Annotation annotation : annotationsOnParameter) {
                    if (JsonProperty.class == annotation.annotationType()) {
                        JsonProperty jsonProperty = (JsonProperty) annotation;

                        // TODO use required attribute of JsonProperty for required fields ->
                        String paramName = jsonProperty.value();
                        MethodParameter methodParameter = new MethodParameter(constructor, paramIndex);

                        parametersInfo.add(new MethodParameterType(paramName, methodParameter));

                        paramIndex++; // increase for each @JsonProperty
                    }
                }
            }
            Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                    + constructor.getName() + " are annotated with @JsonProperty");
        }
    }
    return parametersInfo;
}

From source file:backtype.storm.utils.Utils.java

public static Object newInstance(String klass, Object... params) {
    try {//from w w w  .  jav a 2  s .  c  o  m
        Class c = Class.forName(klass);
        Constructor[] constructors = c.getConstructors();
        boolean found = false;
        Constructor con = null;
        for (Constructor cons : constructors) {
            if (cons.getParameterTypes().length == params.length) {
                con = cons;
                break;
            }
        }

        if (con == null) {
            throw new RuntimeException(
                    "Cound not found the corresponding constructor, params=" + params.toString());
        } else {
            if (con.getParameterTypes().length == 0) {
                return c.newInstance();
            } else {
                return con.newInstance(params);
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.robobinding.util.ConstructorUtils.java

/**
 * <p>//  w w w .  j av  a2 s.  c o m
 * Finds an accessible constructor with compatible parameters.
 * </p>
 * 
 * <p>
 * This checks all the constructor and finds one with compatible parameters
 * This requires that every parameter is assignable from the given parameter
 * types. This is a more flexible search than the normal exact matching
 * algorithm.
 * </p>
 * 
 * <p>
 * First it checks if there is a constructor matching the exact signature.
 * If not then all the constructors of the class are checked to see if their
 * signatures are assignment compatible with the parameter types. The first
 * assignment compatible matching constructor is returned.
 * </p>
 * 
 * @param <T>
 *            the constructor type
 * @param cls
 *            the class to find a constructor for, not null
 * @param parameterTypes
 *            find method with compatible parameters
 * @return the constructor, null if no matching accessible constructor found
 */
public static <T> Constructor<T> getMatchingAccessibleConstructor(final Class<T> cls,
        final Class<?>... parameterTypes) {
    // see if we can find the constructor directly
    // most of the time this works and it's much faster
    try {
        final Constructor<T> ctor = cls.getConstructor(parameterTypes);
        MemberUtils.setAccessibleWorkaround(ctor);
        return ctor;
    } catch (final NoSuchMethodException e) { // NOPMD - Swallow
    }
    Constructor<T> result = null;
    /*
     * (1) Class.getConstructors() is documented to return Constructor<T> so
     * as long as the array is not subsequently modified, everything's fine.
     */
    final Constructor<?>[] ctors = cls.getConstructors();

    // return best match:
    for (Constructor<?> ctor : ctors) {
        // compare parameters
        if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes(), true)) {
            // get accessible version of constructor
            ctor = getAccessibleConstructor(ctor);
            if (ctor != null) {
                MemberUtils.setAccessibleWorkaround(ctor);
                if (result == null || MemberUtils.compareParameterTypes(ctor.getParameterTypes(),
                        result.getParameterTypes(), parameterTypes) < 0) {
                    // temporary variable for annotation, see comment above
                    // (1)
                    @SuppressWarnings("unchecked")
                    final Constructor<T> constructor = (Constructor<T>) ctor;
                    result = constructor;
                }
            }
        }
    }
    return result;
}

From source file:adalid.core.XS1.java

static Class<?> getConstructorParameterType(Class<?> wrapper, Class<?> wrappable) {
    Class<?> parameterType = null;
    Constructor<?>[] constructors = wrapper.getConstructors();
    for (Constructor<?> constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(wrappable)) {
            if (parameterType == null || parameterType.isAssignableFrom(parameterTypes[0])) {
                parameterType = parameterTypes[0];
            }//  ww  w  .j a  v a  2s. co m
        }
    }
    return parameterType;
}

From source file:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Finds a constructor which either does not take any arguments, or does only takes string arguments. Any
 * constructor which does has other arguments than string is ignored.
 *
 * @param c The class to retrieve the constructor from.
 * @return The string argument based constructor of the class.
 * @throws UnknownID If no valid constructor can be found.
 *//*from   w  w  w.j  a  v  a  2  s.co  m*/
@SuppressWarnings("rawtypes")
private static Constructor findStringConstructor(Class c) throws UnknownID {
    for (Constructor con : c.getConstructors()) {
        boolean valid = true;

        // validate the parameter classes. Ignore if not string.
        for (Class cl : con.getParameterTypes()) {
            if (!cl.equals(java.lang.String.class)) {
                valid = false;
                break;
            }
        }
        if (valid) {
            return con;
        }
    }

    // throw an exception if no valid constructor can be found.
    throw new UnknownID("No valid constructor can be found for class '" + c.getName() + "'.");
}

From source file:org.pantsbuild.tools.junit.impl.ConsoleRunnerImpl.java

private static boolean isTest(final Class<?> clazz) {
    // Must be a public concrete class to be a runnable junit Test.
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())
            || !Modifier.isPublic(clazz.getModifiers())) {
        return false;
    }/*www.j a  va2 s  .com*/

    // The class must have some public constructor to be instantiated by the runner being used
    if (!Iterables.any(Arrays.asList(clazz.getConstructors()), IS_PUBLIC_CONSTRUCTOR)) {
        return false;
    }

    // Support junit 3.x Test hierarchy.
    if (junit.framework.Test.class.isAssignableFrom(clazz)) {
        return true;
    }

    // Support classes using junit 4.x custom runners.
    if (clazz.isAnnotationPresent(RunWith.class)) {
        return true;
    }

    // Support junit 4.x @Test annotated methods.
    return Iterables.any(Arrays.asList(clazz.getMethods()), IS_ANNOTATED_TEST_METHOD);
}