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:net.lightbody.bmp.proxy.jetty.xml.XmlConfiguration.java

private Object newObj(Object obj, XmlParser.Node node) throws NoSuchMethodException, ClassNotFoundException,
        InvocationTargetException, IllegalAccessException {
    Class oClass = nodeClass(node);
    String id = node.getAttribute("id");
    int size = 0;
    int argi = node.size();
    for (int i = 0; i < node.size(); i++) {
        Object o = node.get(i);/*from   w  ww  .  ja v a2  s  .c  om*/
        if (o instanceof String)
            continue;
        if (!((XmlParser.Node) o).getTag().equals("Arg")) {
            argi = i;
            break;
        }
        size++;
    }

    Object[] arg = new Object[size];
    for (int i = 0, j = 0; j < size; i++) {
        Object o = node.get(i);
        if (o instanceof String)
            continue;
        arg[j++] = value(obj, (XmlParser.Node) o);
    }

    if (log.isDebugEnabled())
        log.debug("new " + oClass);

    // Lets just try all constructors for now
    Constructor[] constructors = oClass.getConstructors();
    for (int c = 0; constructors != null && c < constructors.length; c++) {
        if (constructors[c].getParameterTypes().length != size)
            continue;

        Object n = null;
        boolean called = false;
        try {
            n = constructors[c].newInstance(arg);
            called = true;
        } catch (IllegalAccessException e) {
            LogSupport.ignore(log, e);
        } catch (InstantiationException e) {
            LogSupport.ignore(log, e);
        } catch (IllegalArgumentException e) {
            LogSupport.ignore(log, e);
        }
        if (called) {
            if (id != null)
                _idMap.put(id, n);
            configure(n, node, argi);
            return n;
        }
    }

    throw new IllegalStateException("No Constructor: " + node + " on " + obj);
}

From source file:org.kuali.rice.krad.service.impl.DocumentServiceImpl.java

private DocumentEvent generateKualiDocumentEvent(Document document, Class<? extends DocumentEvent> eventClass)
        throws ConfigurationException {
    String potentialErrorMessage = "Found error trying to generate Kuali Document Event using event class '"
            + eventClass.getName() + "' for document " + document.getDocumentNumber();

    try {//from  w  w  w. j  av  a2  s. c  o  m
        Constructor<?> usableConstructor = null;
        List<Object> paramList = new ArrayList<Object>();
        for (Constructor<?> currentConstructor : eventClass.getConstructors()) {
            for (Class<?> parameterClass : currentConstructor.getParameterTypes()) {
                if (Document.class.isAssignableFrom(parameterClass)) {
                    usableConstructor = currentConstructor;
                    paramList.add(document);
                } else {
                    paramList.add(null);
                }
            }
            if (KRADUtils.isNotNull(usableConstructor)) {
                break;
            }
        }
        if (usableConstructor == null) {
            throw new RuntimeException("Cannot find a constructor for class '" + eventClass.getName()
                    + "' that takes in a document parameter");
        }
        return (DocumentEvent) usableConstructor.newInstance(paramList.toArray());
    } catch (SecurityException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (IllegalArgumentException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (InstantiationException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (IllegalAccessException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    } catch (InvocationTargetException e) {
        throw new ConfigurationException(potentialErrorMessage, e);
    }
}

From source file:org.latticesoft.util.common.ClassUtil.java

/**
 * Instantiate a new object from a string value
 * //from ww w .  ja va2  s .  c  o  m
 */
public static Object newInstance(String type, String value, String format) {
    Object o = null;
    Class clazz = null;
    if (type == null || value == null) {
        return null;
    }
    if (type.equals("java.lang.String")) {
        return value;
    }
    try {
        clazz = Class.forName(type);
        if ("java.lang.Character".equals(type)) {
            o = new Character(value.charAt(0));
        } else if ("java.util.Date".equals(type) || "java.sql.Time".equals(type)
                || "java.sql.Timestamp".equals(type)) {
            if (format == null) {
                format = "yyyy-MM-dd HH:mm:ss.SSS";
            }
            DateFormat fmt = new SimpleDateFormat(format);
            try {
                o = fmt.parse(value);
            } catch (ParseException pe) {
            }
            if (o != null && "java.sql.Time".equals(type)) {
                Date d = (Date) o;
                o = new Time(d.getTime());
            }
            if (o != null && "java.sql.Timestamp".equals(type)) {
                Date d = (Date) o;
                o = new Timestamp(d.getTime());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (o != null)
        return o;
    try {
        Method[] m = clazz.getMethods();
        for (int i = 0; i < m.length; i++) {
            if ("fromString".equalsIgnoreCase(m[i].getName())) {
                Object[] args = { value };
                o = m[i].invoke(clazz, args);
                break;
            } else if ("parse".equalsIgnoreCase(m[i].getName())) {
                Object[] args = { value };
                o = m[i].invoke(clazz, args);
                break;
            } else if ("newInstance".equalsIgnoreCase(m[i].getName())) {
                Object[] args = { value };
                o = m[i].invoke(clazz, args);
                break;
            } else if ("valueOf".equalsIgnoreCase(m[i].getName())) {
                Object[] args = { value };
                o = m[i].invoke(clazz, args);
                break;
            }
        }
    } catch (Exception e) {
    }

    if (o != null) {
        return o;
    }
    try {
        Constructor[] c = clazz.getConstructors();
        for (int i = 0; i < c.length; i++) {
            Class[] param = c[i].getParameterTypes();
            if (param != null && param.length == 1 && param[0].getName().equals("java.lang.String")) {
                Object[] args = { value };
                o = c[i].newInstance(args);
            }
        }
    } catch (Exception e) {
    }

    if (o == null) {
        o = value;
    }
    return o;
}

From source file:adalid.commons.velocity.Writer.java

private 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];
            }//w  ww. jav a2 s.c o m
        }
    }
    return parameterType;
}

From source file:org.obsidian.test.TestAbstract.java

public <T> String buildConstructionStringFromType(Class<T> type, Constructor[] visitedConstructors) {

    //initialize construction String 
    String constructionString;//from  ww  w .  j a  v a 2s  .  c  om

    //append equality method types
    appendEqualityMethodTypes(type);

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    //if class is abstract, replace with concrete substitution
    if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        type = Helpers.getConcreteSubstitution(type);
    }

    //type's simple name
    String name = type.getSimpleName();

    //append the type to the getterTest's dynamic imports
    appendDynamicImports(type);

    if (Helpers.PRIMITIVE_CONSTRUCTIONS.get(name) != null) {
        //get construction from PRIMITIVE_CONSTRUCTIONS
        constructionString = Helpers.PRIMITIVE_CONSTRUCTIONS.get(name);
    } else if (type.isArray()) {
        int numberOfDimensions = StringUtils.countMatches(name, "[]");

        constructionString = name.replace("[]", "");

        for (int i = 0; i < numberOfDimensions; i++) {
            constructionString = constructionString + "[0]";
        }

        constructionString = "new " + constructionString;

    } else if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) {
        constructionString = "null";
    } else if (type.getConstructors().length == 0) {
        constructionString = "null";
    } else {
        //not visited constructors
        ArrayList<Constructor> NVC = Helpers.notVisitedConstructors(type.getConstructors(),
                visitedConstructors);

        Constructor constructor = Helpers.getConstructorWithLeastParametersFromList(NVC);

        if (NVC.isEmpty()) {
            constructionString = "null";
        } else if (constructor.getExceptionTypes().length > 0) {
            constructionString = "null";
        } else {

            visitedConstructors = Helpers.addConstructor(visitedConstructors, constructor);
            constructionString = "new " + name + "(";
            Class[] parameters = constructor.getParameterTypes();
            for (int i = 0; i < parameters.length; i++) {
                constructionString = constructionString
                        + buildConstructionStringFromType(parameters[i], visitedConstructors) + ",";
            }
            if (parameters.length != 0) {
                constructionString = constructionString.substring(0, constructionString.length() - 1);
            }
            constructionString = constructionString + ")";
        }
    }

    //this will prevent ambiguity in constructors with parmeter that 
    //cannot be constructed
    if (constructionString.contains("null")) {
        constructionString = "null";
    }

    return constructionString;
}

From source file:org.ramadda.util.Utils.java

/**
 * _more_/*ww w .  j a  v a  2s.c  o  m*/
 *
 * @param c _more_
 * @param paramTypes _more_
 *
 * @return _more_
 */
public static Constructor findConstructor(Class c, Class[] paramTypes) {
    ArrayList<Object> allCtors = new ArrayList<Object>();
    Constructor[] constructors = c.getConstructors();
    if (constructors.length == 0) {
        System.err.println("*** Could not find any constructors for class:" + c.getName());

        return null;
    }
    for (int i = 0; i < constructors.length; i++) {
        if (typesMatch(constructors[i].getParameterTypes(), paramTypes)) {
            allCtors.add(constructors[i]);
        }
    }
    if (allCtors.size() > 1) {
        throw new IllegalArgumentException("More than one constructors matched for class:" + c.getName());
    }
    if (allCtors.size() == 1) {
        return (Constructor) allCtors.get(0);
    }

    for (int i = 0; i < constructors.length; i++) {
        Class[] formals = constructors[i].getParameterTypes();
        for (int j = 0; j < formals.length; j++) {
            System.err.println("param " + j + "  " + formals[j].getName() + " " + paramTypes[j].getName());
        }
    }

    return null;
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Generate the bytecode for a bean proxy for the given type.
 *//*from   w w  w  .j  a  va  2  s .  co m*/
protected BCClass generateProxyBeanBytecode(Class type, boolean runtime) {
    if (Modifier.isFinal(type.getModifiers()))
        return null;
    if (ImplHelper.isManagedType(null, type))
        return null;

    // we can only generate a valid proxy if there is a copy constructor
    // or a default constructor
    Constructor cons = findCopyConstructor(type);
    if (cons == null) {
        Constructor[] cs = type.getConstructors();
        for (int i = 0; cons == null && i < cs.length; i++)
            if (cs[i].getParameterTypes().length == 0)
                cons = cs[i];
        if (cons == null)
            return null;
    }

    Project project = new Project();
    BCClass bc = AccessController
            .doPrivileged(J2DoPrivHelper.loadProjectClassAction(project, getProxyClassName(type, runtime)));
    bc.setSuperclass(type);
    bc.declareInterface(ProxyBean.class);

    delegateConstructors(bc, type);
    addProxyMethods(bc, true);
    addProxyBeanMethods(bc, type, cons);
    if (!proxySetters(bc, type))
        return null;
    addWriteReplaceMethod(bc, runtime);
    return bc;
}

From source file:io.milton.config.HttpManagerBuilder.java

private Object createObject(Class c) throws CreationException {
    log.info("createObject: {}", c.getCanonicalName());
    // Look for an @Inject or default constructor
    Constructor found = null;/*from  ww  w .  j a  v  a 2  s  . c o m*/

    for (Constructor con : c.getConstructors()) {
        Annotation[][] paramTypes = con.getParameterAnnotations();
        if (paramTypes != null && paramTypes.length > 0) {
            Annotation inject = con.getAnnotation(Inject.class);
            if (inject != null) {
                found = con;
            }
        } else {
            found = con;
        }
    }
    if (found == null) {
        throw new RuntimeException(
                "Could not find a default or @Inject constructor for class: " + c.getCanonicalName());
    }
    Object args[] = new Object[found.getParameterTypes().length];
    int i = 0;
    for (Class paramType : found.getParameterTypes()) {
        try {
            args[i++] = findOrCreateObject(paramType);
        } catch (CreationException ex) {
            throw new CreationException(c, ex);
        }
    }
    Object created;
    try {
        log.info("Creating: {}", c.getCanonicalName());
        created = found.newInstance(args);
        rootContext.put(created);
    } catch (InstantiationException ex) {
        throw new CreationException(c, ex);
    } catch (IllegalAccessException ex) {
        throw new CreationException(c, ex);
    } catch (IllegalArgumentException ex) {
        throw new CreationException(c, ex);
    } catch (InvocationTargetException ex) {
        throw new CreationException(c, ex);
    }
    // Now look for @Inject fields
    for (Field field : c.getDeclaredFields()) {
        Inject anno = field.getAnnotation(Inject.class);
        if (anno != null) {
            boolean acc = field.isAccessible();
            try {
                field.setAccessible(true);
                field.set(created, findOrCreateObject(field.getType()));
            } catch (IllegalArgumentException ex) {
                throw new CreationException(field, c, ex);
            } catch (IllegalAccessException ex) {
                throw new CreationException(field, c, ex);
            } finally {
                field.setAccessible(acc); // put back the way it was
            }
        }
    }

    // Finally set any @Inject methods
    for (Method m : c.getMethods()) {
        Inject anno = m.getAnnotation(Inject.class);
        if (anno != null) {
            Object[] methodArgs = new Object[m.getParameterTypes().length];
            int ii = 0;
            try {
                for (Class<?> paramType : m.getParameterTypes()) {
                    methodArgs[ii++] = findOrCreateObject(paramType);
                }
                m.invoke(created, methodArgs);
            } catch (CreationException creationException) {
                throw new CreationException(m, c, creationException);
            } catch (IllegalAccessException ex) {
                throw new CreationException(m, c, ex);
            } catch (IllegalArgumentException ex) {
                throw new CreationException(m, c, ex);
            } catch (InvocationTargetException ex) {
                throw new CreationException(m, c, ex);
            }
        }
    }
    if (created instanceof InitListener) {
        if (listeners == null) {
            listeners = new ArrayList<InitListener>();
        }
        InitListener l = (InitListener) created;
        l.beforeInit(this); // better late then never!!
        listeners.add(l);
    }
    return created;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private Object makeNewInstance(Class expectedClass, HashMap<String, Object> jsData)
        throws ApplicationException {
    Object val = null;
    try {//from  w  w w  . j a  v a 2s  . c  o m
        Constructor[] constructors = expectedClass.getConstructors();
        for (int k = 0; k < constructors.length; k++) {
            Constructor constructor = constructors[k];
            Annotation[][] constrAnnot = constructor.getParameterAnnotations();
            String[] paramNames = new String[constrAnnot.length];
            int annotCount = 0;
            for (int i = 0; i < constrAnnot.length; i++) {
                Annotation[] annotations = constrAnnot[i];
                for (int j = 0; j < annotations.length; j++) {
                    Annotation annotation = annotations[j];
                    if (annotation instanceof Name) {
                        paramNames[i] = ((Name) annotation).value();
                        paramNames[i] = paramNames[i].startsWith("xxx") ? paramNames[i].substring(3)
                                : paramNames[i];
                        annotCount++;
                        break;
                    }
                }
            }
            if (annotCount != constrAnnot.length) {
                continue;
            }
            Object[] params = prepareMethodParam(jsData, false, paramNames, constructor.getParameterTypes());
            if (params != null) {
                val = constructor.newInstance(params);
                break;
            }
        }

        if (val == null) {
            throw new Exception("Can't create instance of class " + expectedClass.getName());
        }
    } catch (Exception ex) {
        throw new ApplicationException(ex.getMessage(), "ERR9001", ex);
    }

    return val;
}