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:org.kie.scanner.KieRepositoryScannerTest.java

private void testKScannerWithKJarContainingClassLoadedFromClassLoader(boolean differentKbases)
        throws Exception {
    // DROOLS-1231
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");

    InternalKieModule kJar1 = createKieJarWithJavaClass(ks, releaseId, "KBase1", 7);

    KieMavenRepository repository = getKieMavenRepository();
    repository.installArtifact(releaseId, kJar1, createKPom(fileManager, releaseId));
    ks.getRepository().removeKieModule(releaseId);

    KieContainer kieContainer = ks.newKieContainer(releaseId);
    KieScanner scanner = ks.newKieScanner(kieContainer);

    Class<?> beanClass = kieContainer.getClassLoader().loadClass("org.kie.test.Bean");
    KieSession ksession = kieContainer.newKieSession("KSession1");

    Object bean = beanClass.getDeclaredConstructors()[0].newInstance(2);
    ksession.insert(bean);//w ww.j  a  va2 s . com

    checkKSession(ksession, 14);

    InternalKieModule kJar2 = createKieJarWithJavaClass(ks, releaseId, differentKbases ? "KBase2" : "KBase1",
            5);
    repository.installArtifact(releaseId, kJar2, createKPom(fileManager, releaseId));
    ks.getRepository().removeKieModule(releaseId);

    // forces cache of old Bean class definition before updating to newer release
    Class<?> beanClass1 = Class.forName("org.kie.test.Bean", true, kieContainer.getClassLoader());

    kieContainer.updateToVersion(releaseId);

    beanClass = kieContainer.getClassLoader().loadClass("org.kie.test.Bean");
    KieSession ksession2 = kieContainer.newKieSession("KSession1");

    bean = beanClass.getDeclaredConstructors()[0].newInstance(3);
    ksession2.insert(bean);

    checkKSession(ksession2, 15);

    ks.getRepository().removeKieModule(releaseId);
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();/*  w ww.  j ava 2  s . c  om*/
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

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

/**
 * Creates an object instance.//from   ww w.j  a v a2s.c  o m
 * 
 * @param clazz
 *            the object class type
 * @param args
 *            the arguments of the constructor need to be use to instantiate
 *            bean. instance.
 * @return tr v? i tng Object va c khi to.
 */
@SuppressWarnings("unchecked")
public static <T> T createInstance(Class<T> clazz, Object... args) {

    T result = null;
    try {
        Constructor<T> constructor = null;
        if (args == null) {
            constructor = clazz.getDeclaredConstructor();
        } else {
            List<Class<?>> argsType = new ArrayList<Class<?>>();
            for (Object arg : args) {
                argsType.add(arg.getClass());
            }
            constructor = clazz.getDeclaredConstructor(argsType.toArray(new Class<?>[argsType.size()]));
        }
        constructor.setAccessible(true);
        result = args == null ? (T) constructor.newInstance() : constructor.newInstance(args);
    } catch (InstantiationException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (IllegalAccessException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (SecurityException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (NoSuchMethodException e) {
        if (args != null) {
            for (Constructor<?> cons : clazz.getDeclaredConstructors()) {
                cons.setAccessible(true);
                try {
                    result = (T) cons.newInstance(args);
                } catch (IllegalArgumentException e1) {
                    continue;
                } catch (InstantiationException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                } catch (IllegalAccessException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                } catch (InvocationTargetException e1) {
                    if (log.isFatalEnabled()) {
                        log.fatal("Could not create instance basing on target class ['" + clazz + "']", e1);
                    }
                }
            }
            if (result == null) {
                if (log.isFatalEnabled()) {
                    log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
                }
            }
        } else {
            if (log.isFatalEnabled()) {
                log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
            }
        }
    } catch (IllegalArgumentException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    } catch (InvocationTargetException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create instance basing on target class ['" + clazz + "']", e);
        }
    }
    return result;
}

From source file:org.freebxml.omar.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Given a Binding object returns the OMARDAO for that object.
 *
 *///ww w  .ja v  a 2 s  .co m
private OMARDAO getDAOForObject(RegistryObjectType ro, ServerRequestContext context) throws RegistryException {
    OMARDAO dao = null;

    try {
        String bindingClassName = ro.getClass().getName();
        String daoClassName = bindingClassName.substring(bindingClassName.lastIndexOf('.') + 1,
                bindingClassName.length() - 4);

        //Construct the corresonding DAO instance using reflections
        Class daoClazz = Class.forName("org.freebxml.omar.server.persistence.rdb." + daoClassName + "DAO");

        Class[] conParameterTypes = new Class[1];
        conParameterTypes[0] = context.getClass();
        Object[] conParameterValues = new Object[1];
        conParameterValues[0] = context;
        Constructor[] cons = daoClazz.getDeclaredConstructors();

        //Find the constructor that takes RequestContext as its only arg
        Constructor con = null;
        for (int i = 0; i < cons.length; i++) {
            con = cons[i];
            if ((con.getParameterTypes().length == 1) && (con.getParameterTypes()[0] == conParameterTypes[0])) {
                dao = (OMARDAO) con.newInstance(conParameterValues);
                break;
            }
        }

    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return dao;

}

From source file:it.cnr.icar.eric.server.persistence.rdb.SQLPersistenceManagerImpl.java

/**
 * Given a Binding object returns the OMARDAO for that object.
 * /*from w  ww  .ja va 2  s.  c o  m*/
 */
private OMARDAO getDAOForObject(RegistryObjectType ro, ServerRequestContext context) throws RegistryException {
    OMARDAO dao = null;

    try {
        @SuppressWarnings("unused")
        String bindingClassName = ro.getClass().getName();

        // reuse same mapper as for tablenames
        // this handles Type1 endings correctly

        String daoClassName = Utility.getInstance().mapDAOName(ro);

        // Construct the corresponding DAO instance using reflections
        Class<?> daoClazz = Class.forName("it.cnr.icar.eric.server.persistence.rdb." + daoClassName + "DAO");

        Class<?>[] conParameterTypes = new Class[1];
        conParameterTypes[0] = context.getClass();
        Object[] conParameterValues = new Object[1];
        conParameterValues[0] = context;
        Constructor<?>[] cons = daoClazz.getDeclaredConstructors();

        // Find the constructor that takes RequestContext as its only arg
        Constructor<?> con = null;
        for (int i = 0; i < cons.length; i++) {
            con = cons[i];
            if ((con.getParameterTypes().length == 1) && (con.getParameterTypes()[0] == conParameterTypes[0])) {
                dao = (OMARDAO) con.newInstance(conParameterValues);
                break;
            }
        }

    } catch (Exception e) {
        throw new RegistryException(e);
    }

    return dao;

}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean checkConstructor(Constructor c, Class clss, List<Class> classes) {
    if (!Modifier.isPublic(c.getModifiers())) {
        if (c.getParameterTypes().length != 0 || !Modifier.isProtected(c.getModifiers())) {
            return true;
        }/* w ww.  ja  va  2 s.c  o  m*/
    }
    Constructor ca[] = clss.getDeclaredConstructors();
    for (int i = 0; i < ca.length; i++) {
        Constructor constructor = ca[i];
        if (constructor.equals(c)) {
            break;
        }
        if (constructor.getParameterTypes().length == c.getParameterTypes().length) {
            if (c.getParameterTypes().length >= 1
                    && String.class.isAssignableFrom(c.getParameterTypes()[0]) != String.class
                            .isAssignableFrom(constructor.getParameterTypes()[0])) {
                continue;
            }
            return true;
        }
    }
    if (c.getParameterTypes().length == 1 && clss.isAssignableFrom(c.getParameterTypes()[0])) {
        return true;
    }
    if (!checkParameters(c.getParameterTypes(), classes)) {
        return true;
    }
    return false;
}

From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java

/**
 * Test for {@link ReflectionUtils#getShortestConstructor(Class)}.
 *//*from   w  w w  . j a v  a 2  s.c o  m*/
public void test_getShortestConstructor() throws Exception {
    Class<Class_getShortestConstructor> clazz = Class_getShortestConstructor.class;
    // check that longer constructor is before shorter
    {
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        assertThat(constructors[0].getParameterTypes()).hasSize(2);
        assertThat(constructors[1].getParameterTypes()).hasSize(1);
    }
    // do test
    {
        Constructor<?> constructor = ReflectionUtils.getShortestConstructor(clazz);
        assertThat(constructor.getParameterTypes()).hasSize(1);
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    // request windows line breaks to make the files easier to edit (in particular the marshalled .xml files)
    System.setProperty("line.separator", "\r\n");

    // get a reference to the servlet context
    ServletContext servletContext = event.getServletContext();

    // set up logging
    try {// ww w.j a  va 2  s  .co  m

        // set the log path
        System.setProperty("logPath", servletContext.getRealPath("/") + "/WEB-INF/logs/Rapid.log");

        // get a logger
        _logger = Logger.getLogger(RapidHttpServlet.class);

        // set the logger and store in servletConext
        servletContext.setAttribute("logger", _logger);

        // log!
        _logger.info("Logger created");

    } catch (Exception e) {

        System.err.println("Error initilising logging : " + e.getMessage());

        e.printStackTrace();
    }

    try {

        // we're looking for a password and salt for the encryption
        char[] password = null;
        byte[] salt = null;
        // look for the rapid.txt file with the saved password and salt
        File secretsFile = new File(servletContext.getRealPath("/") + "/WEB-INF/security/encryption.txt");
        // if it exists
        if (secretsFile.exists()) {
            // get a file reader
            BufferedReader br = new BufferedReader(new FileReader(secretsFile));
            // read the first line
            String className = br.readLine();
            // read the next line
            String s = br.readLine();
            // close the reader
            br.close();

            try {
                // get the class 
                Class classClass = Class.forName(className);
                // get the interfaces
                Class[] classInterfaces = classClass.getInterfaces();
                // assume it doesn't have the interface we want
                boolean gotInterface = false;
                // check we got some
                if (classInterfaces != null) {
                    for (Class classInterface : classInterfaces) {
                        if (com.rapid.utils.Encryption.EncryptionProvider.class.equals(classInterface)) {
                            gotInterface = true;
                            break;
                        }
                    }
                }
                // check the class extends com.rapid.Action
                if (gotInterface) {
                    // get the constructors
                    Constructor[] classConstructors = classClass.getDeclaredConstructors();
                    // check we got some
                    if (classConstructors != null) {
                        // assume we don't get the parameterless one we need
                        Constructor constructor = null;
                        // loop them
                        for (Constructor classConstructor : classConstructors) {
                            // check parameters
                            if (classConstructor.getParameterTypes().length == 0) {
                                constructor = classConstructor;
                                break;
                            }
                        }
                        // check we got what we want
                        if (constructor == null) {
                            _logger.error(
                                    "Encyption not initialised : Class in security.txt class must have a parameterless constructor");
                        } else {
                            // construct the class
                            EncryptionProvider encryptionProvider = (EncryptionProvider) constructor
                                    .newInstance();
                            // get the password
                            password = encryptionProvider.getPassword();
                            // get the salt
                            salt = encryptionProvider.getSalt();
                            // log
                            _logger.info("Encyption initialised");
                        }
                    }
                } else {
                    _logger.error(
                            "Encyption not initialised : Class in security.txt class must extend com.rapid.utils.Encryption.EncryptionProvider");
                }
            } catch (Exception ex) {
                _logger.error("Encyption not initialised : " + ex.getMessage(), ex);
            }
        } else {
            _logger.info("Encyption not initialised");
        }

        // create the encypted xml adapter (if the file above is not found there no encryption will occur)
        RapidHttpServlet.setEncryptedXmlAdapter(new EncryptedXmlAdapter(password, salt));

        // initialise the schema factory (we'll reuse it in the various loaders)
        _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

        // initialise the list of classes we're going to want in the JAXB context (the loaders will start adding to it)
        _jaxbClasses = new ArrayList<Class>();

        _logger.info("Loading database drivers");

        // load the database drivers first
        loadDatabaseDrivers(servletContext);

        _logger.info("Loading connection adapters");

        // load the connection adapters 
        loadConnectionAdapters(servletContext);

        _logger.info("Loading security adapters");

        // load the security adapters 
        loadSecurityAdapters(servletContext);

        _logger.info("Loading form adapters");

        // load the form adapters
        loadFormAdapters(servletContext);

        _logger.info("Loading actions");

        // load the actions 
        loadActions(servletContext);

        _logger.info("Loading templates");

        // load templates
        loadThemes(servletContext);

        _logger.info("Loading controls");

        // load the controls 
        loadControls(servletContext);

        // add some classes manually
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.NameRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxOccursRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MaxLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.MinLengthRestriction.class);
        _jaxbClasses.add(com.rapid.soa.SOAElementRestriction.EnumerationRestriction.class);
        _jaxbClasses.add(com.rapid.soa.Webservice.class);
        _jaxbClasses.add(com.rapid.soa.SQLWebservice.class);
        _jaxbClasses.add(com.rapid.soa.JavaWebservice.class);
        _jaxbClasses.add(com.rapid.core.Validation.class);
        _jaxbClasses.add(com.rapid.core.Action.class);
        _jaxbClasses.add(com.rapid.core.Event.class);
        _jaxbClasses.add(com.rapid.core.Style.class);
        _jaxbClasses.add(com.rapid.core.Control.class);
        _jaxbClasses.add(com.rapid.core.Page.class);
        _jaxbClasses.add(com.rapid.core.Application.class);
        _jaxbClasses.add(com.rapid.core.Device.class);
        _jaxbClasses.add(com.rapid.core.Device.Devices.class);

        // convert arraylist to array
        Class[] classes = _jaxbClasses.toArray(new Class[_jaxbClasses.size()]);
        // re-init the JAXB context to include our injectable classes               
        JAXBContext jaxbContext = JAXBContext.newInstance(classes);

        // this logs the JAXB classes
        _logger.trace("JAXB  content : " + jaxbContext.toString());

        // store the jaxb context in RapidHttpServlet
        RapidHttpServlet.setJAXBContext(jaxbContext);

        // load the devices
        Devices.load(servletContext);

        // load the applications!
        loadApplications(servletContext);

        // add some useful global objects 
        servletContext.setAttribute("xmlDateFormatter", new SimpleDateFormat("yyyy-MM-dd"));
        servletContext.setAttribute("xmlDateTimeFormatter", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

        String localDateFormat = servletContext.getInitParameter("localDateFormat");
        if (localDateFormat == null)
            localDateFormat = "dd/MM/yyyy";
        servletContext.setAttribute("localDateFormatter", new SimpleDateFormat(localDateFormat));

        String localDateTimeFormat = servletContext.getInitParameter("localDateTimeFormat");
        if (localDateTimeFormat == null)
            localDateTimeFormat = "dd/MM/yyyy HH:mm a";
        servletContext.setAttribute("localDateTimeFormatter", new SimpleDateFormat(localDateTimeFormat));

        boolean actionCache = Boolean.parseBoolean(servletContext.getInitParameter("actionCache"));
        if (actionCache)
            servletContext.setAttribute("actionCache", new ActionCache(servletContext));

        int pageAgeCheckInterval = MONITOR_CHECK_INTERVAL;
        try {
            String pageAgeCheckIntervalString = servletContext.getInitParameter("pageAgeCheckInterval");
            if (pageAgeCheckIntervalString != null)
                pageAgeCheckInterval = Integer.parseInt(pageAgeCheckIntervalString);
        } catch (Exception ex) {
            _logger.error("pageAgeCheckInterval is not an integer");
        }

        int pageMaxAge = MONITOR_MAX_AGE;
        try {
            String pageMaxAgeString = servletContext.getInitParameter("pageMaxAge");
            if (pageMaxAgeString != null)
                pageMaxAge = Integer.parseInt(pageMaxAgeString);
        } catch (Exception ex) {
            _logger.error("pageMaxAge is not an integer");
        }

        // start the monitor
        _monitor = new Monitor(servletContext, pageAgeCheckInterval, pageMaxAge);
        _monitor.start();

        // allow calling to https without checking certs (for now)
        SSLContext sc = SSLContext.getInstance("SSL");
        TrustManager[] trustAllCerts = new TrustManager[] { new Https.TrustAllCerts() };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    } catch (Exception ex) {

        _logger.error("Error loading applications : " + ex.getMessage());

        ex.printStackTrace();
    }

}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

public void register(ContainerBuilder containerBuilder, LocatableProperties props)
        throws ConfigurationException {
    if (LOG.isInfoEnabled()) {
        LOG.info("Parsing configuration file [" + configFileName + "]");
    }/* www.j  a v  a 2  s  .  c  o  m*/
    Map<String, Node> loadedBeans = new HashMap<String, Node>();
    for (Document doc : documents) {
        Element rootElement = doc.getDocumentElement();
        NodeList children = rootElement.getChildNodes();
        int childSize = children.getLength();

        for (int i = 0; i < childSize; i++) {
            Node childNode = children.item(i);

            if (childNode instanceof Element) {
                Element child = (Element) childNode;

                final String nodeName = child.getNodeName();

                if ("bean".equals(nodeName)) {
                    String type = child.getAttribute("type");
                    String name = child.getAttribute("name");
                    String impl = child.getAttribute("class");
                    String onlyStatic = child.getAttribute("static");
                    String scopeStr = child.getAttribute("scope");
                    boolean optional = "true".equals(child.getAttribute("optional"));
                    Scope scope = Scope.SINGLETON;
                    if ("default".equals(scopeStr)) {
                        scope = Scope.DEFAULT;
                    } else if ("request".equals(scopeStr)) {
                        scope = Scope.REQUEST;
                    } else if ("session".equals(scopeStr)) {
                        scope = Scope.SESSION;
                    } else if ("singleton".equals(scopeStr)) {
                        scope = Scope.SINGLETON;
                    } else if ("thread".equals(scopeStr)) {
                        scope = Scope.THREAD;
                    }

                    if (StringUtils.isEmpty(name)) {
                        name = Container.DEFAULT_NAME;
                    }

                    try {
                        Class cimpl = ClassLoaderUtil.loadClass(impl, getClass());
                        Class ctype = cimpl;
                        if (StringUtils.isNotEmpty(type)) {
                            ctype = ClassLoaderUtil.loadClass(type, getClass());
                        }
                        if ("true".equals(onlyStatic)) {
                            // Force loading of class to detect no class def found exceptions
                            cimpl.getDeclaredClasses();
                            containerBuilder.injectStatics(cimpl);
                        } else {
                            if (containerBuilder.contains(ctype, name)) {
                                Location loc = LocationUtils
                                        .getLocation(loadedBeans.get(ctype.getName() + name));
                                if (throwExceptionOnDuplicateBeans) {
                                    throw new ConfigurationException("Bean type " + ctype + " with the name "
                                            + name + " has already been loaded by " + loc, child);
                                }
                            }

                            // Force loading of class to detect no class def found exceptions
                            cimpl.getDeclaredConstructors();

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Loaded type:" + type + " name:" + name + " impl:" + impl);
                            }
                            containerBuilder.factory(ctype, name,
                                    new LocatableFactory(name, ctype, cimpl, scope, childNode), scope);
                        }
                        loadedBeans.put(ctype.getName() + name, child);
                    } catch (Throwable ex) {
                        if (!optional) {
                            throw new ConfigurationException(
                                    "Unable to load bean: type:" + type + " class:" + impl, ex, childNode);
                        } else {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Unable to load optional class: #0", impl);
                            }
                        }
                    }
                } else if ("constant".equals(nodeName)) {
                    String name = child.getAttribute("name");
                    String value = child.getAttribute("value");
                    props.setProperty(name, value, childNode);
                } else if (nodeName.equals("unknown-handler-stack")) {
                    List<UnknownHandlerConfig> unknownHandlerStack = new ArrayList<UnknownHandlerConfig>();
                    NodeList unknownHandlers = child.getElementsByTagName("unknown-handler-ref");
                    int unknownHandlersSize = unknownHandlers.getLength();

                    for (int k = 0; k < unknownHandlersSize; k++) {
                        Element unknownHandler = (Element) unknownHandlers.item(k);
                        unknownHandlerStack.add(new UnknownHandlerConfig(unknownHandler.getAttribute("name")));
                    }

                    if (!unknownHandlerStack.isEmpty())
                        configuration.setUnknownHandlerStack(unknownHandlerStack);
                }
            }
        }
    }
}

From source file:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java

@Override
@Nullable/*from w  w  w .j  a  v a  2  s .  c  o m*/
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
        throws BeanCreationException {

    // Let's check for lookup methods here..
    if (!this.lookupMethodsChecked.contains(beanName)) {
        try {
            ReflectionUtils.doWithMethods(beanClass, method -> {
                Lookup lookup = method.getAnnotation(Lookup.class);
                if (lookup != null) {
                    Assert.state(beanFactory != null, "No BeanFactory available");
                    LookupOverride override = new LookupOverride(method, lookup.value());
                    try {
                        RootBeanDefinition mbd = (RootBeanDefinition) beanFactory
                                .getMergedBeanDefinition(beanName);
                        mbd.getMethodOverrides().addOverride(override);
                    } catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(beanName,
                                "Cannot apply @Lookup to beans without corresponding bean definition");
                    }
                }
            });
        } catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
        }
        this.lookupMethodsChecked.add(beanName);
    }

    // Quick check on the concurrent map first, with minimal locking.
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates;
                try {
                    rawCandidates = beanClass.getDeclaredConstructors();
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                    + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                            ex);
                }
                List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                int nonSyntheticConstructors = 0;
                for (Constructor<?> candidate : rawCandidates) {
                    if (!candidate.isSynthetic()) {
                        nonSyntheticConstructors++;
                    } else if (primaryConstructor != null) {
                        continue;
                    }
                    AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor = userClass
                                        .getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            } catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    if (ann != null) {
                        if (requiredConstructor != null) {
                            throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: "
                                    + candidate
                                    + ". Found constructor with 'required' Autowired annotation already: "
                                    + requiredConstructor);
                        }
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructors: " + candidates
                                                + ". Found constructor with 'required' Autowired annotation: "
                                                + candidate);
                            }
                            requiredConstructor = candidate;
                        }
                        candidates.add(candidate);
                    } else if (candidate.getParameterCount() == 0) {
                        defaultConstructor = candidate;
                    }
                }
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    if (requiredConstructor == null) {
                        if (defaultConstructor != null) {
                            candidates.add(defaultConstructor);
                        } else if (candidates.size() == 1 && logger.isWarnEnabled()) {
                            logger.warn("Inconsistent constructor declaration on bean with name '" + beanName
                                    + "': single autowire-marked constructor flagged as optional - "
                                    + "this constructor is effectively required since there is no "
                                    + "default constructor to fall back to: " + candidates.get(0));
                        }
                    }
                    candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
                } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                    candidateConstructors = new Constructor<?>[] { rawCandidates[0] };
                } else if (nonSyntheticConstructors == 2 && primaryConstructor != null
                        && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor };
                } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor };
                } else {
                    candidateConstructors = new Constructor<?>[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}