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.mirth.connect.client.ui.LoadedExtensions.java

public void initialize() {
    // Remove all existing extensions from the maps in case they are being
    // initialized again
    clearExtensionMaps();//w w w  . j  a va 2  s.  c  o  m

    // Order all the plugins by their weight before loading any of them.
    Map<String, String> pluginNameMap = new HashMap<String, String>();
    NavigableMap<Integer, List<String>> weightedPlugins = new TreeMap<Integer, List<String>>();
    for (PluginMetaData metaData : PlatformUI.MIRTH_FRAME.getPluginMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (metaData.getClientClasses() != null) {
                    for (PluginClass pluginClass : metaData.getClientClasses()) {
                        String clazzName = pluginClass.getName();
                        int weight = pluginClass.getWeight();
                        pluginNameMap.put(clazzName, metaData.getName());

                        List<String> classList = weightedPlugins.get(weight);
                        if (classList == null) {
                            classList = new ArrayList<String>();
                            weightedPlugins.put(weight, classList);
                        }

                        classList.add(clazzName);
                    }
                }

                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e);
        }
    }

    // Load connector code template plugins before anything else
    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {
                extensionVersions.put(metaData.getName(), metaData.getPluginVersion());
                if (StringUtils.isNotEmpty(metaData.getTemplateClassName())) {
                    Class<?> clazz = Class.forName(metaData.getTemplateClassName());

                    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
                        if (constructor.getParameterTypes().length == 1) {
                            CodeTemplatePlugin codeTemplatePlugin = (CodeTemplatePlugin) constructor
                                    .newInstance(new Object[] { metaData.getName() });
                            addPluginPoints(codeTemplatePlugin);
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load code template plugin: " + metaData.getTemplateClassName());
        }
    }

    // Signal the reference list factory that code template plugins have been loaded
    ReferenceListFactory.getInstance().loadPluginReferences();

    // Load the plugins in order of their weight
    for (List<String> classList : weightedPlugins.descendingMap().values()) {
        for (String clazzName : classList) {
            try {
                String pluginName = pluginNameMap.get(clazzName);
                Class<?> clazz = Class.forName(clazzName);
                Constructor<?>[] constructors = clazz.getDeclaredConstructors();

                for (int i = 0; i < constructors.length; i++) {
                    Class<?> parameters[];
                    parameters = constructors[i].getParameterTypes();
                    // load plugin if the number of parameters
                    // in the constructor is 1.
                    if (parameters.length == 1) {
                        ClientPlugin clientPlugin = (ClientPlugin) constructors[i]
                                .newInstance(new Object[] { pluginName });
                        addPluginPoints(clientPlugin);
                        i = constructors.length;
                    }
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                        "Could not load plugin class: " + clazzName);
            }
        }
    }

    for (ConnectorMetaData metaData : PlatformUI.MIRTH_FRAME.getConnectorMetaData().values()) {
        try {
            if (PlatformUI.MIRTH_FRAME.mirthClient.isExtensionEnabled(metaData.getName())) {

                String connectorName = metaData.getName();
                ConnectorSettingsPanel connectorSettingsPanel = (ConnectorSettingsPanel) Class
                        .forName(metaData.getClientClassName()).newInstance();

                if (metaData.getType() == ConnectorMetaData.Type.SOURCE) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    sourceConnectors.put(connectorName, connectorSettingsPanel);
                } else if (metaData.getType() == ConnectorMetaData.Type.DESTINATION) {
                    connectors.put(connectorName, connectorSettingsPanel);
                    destinationConnectors.put(connectorName, connectorSettingsPanel);
                } else {
                    // type must be SOURCE or DESTINATION
                    throw new Exception();
                }
            }
        } catch (Exception e) {
            PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, e,
                    "Could not load connector class: " + metaData.getClientClassName());
        }
    }

    // Signal the reference list factory that all other plugins have been loaded
    ReferenceListFactory.getInstance().loadReferencesAfterPlugins();
}

From source file:org.powertac.logtool.common.DomainObjectReader.java

private Object constructInstance(Class<?> clazz, String[] args) throws MissingDomainObject {
    Constructor<?>[] potentials = clazz.getDeclaredConstructors();
    Constructor<?> target = null;
    Object[] params = null;//from w  w  w. j av  a  2  s.co m
    for (Constructor<?> cons : potentials) {
        Type[] types = cons.getGenericParameterTypes();
        if (types.length != args.length)
            // not this one
            continue;
        // correct length of parameter list -
        // now try to resolve the types.
        // If we get a MissingDomainObject exception, keep going.
        try {
            params = resolveArgs(types, args);
        } catch (MissingDomainObject mdo) {
            // ignore
        }
        if (null == params)
            // no match
            continue;
        else {
            target = cons;
            break;
        }
    }
    // if we found one, use it, then update the id value
    if (null != target) {
        Object result = null;
        try {
            target.setAccessible(true);
            result = target.newInstance(params);
        } catch (InvocationTargetException ite) {
            // arg-constructor mismatch
            return restoreInstance(clazz, args);
        } catch (Exception e) {
            log.error("could not construct instance of " + clazz.getName() + ": " + e.toString());
            return null;
        }
        return result;
    } else {
        // otherwise, try to use the readResolve method
        return restoreInstance(clazz, args);
    }
}

From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java

/**
 * Parses the methods which should be considered in coverage.
 *
 * @param annotation/*from  ww  w  .  j a va 2  s  .  c  o  m*/
 *            the {@link SetteIncludeCoverage} annotation
 * @param v
 *            a {@link MethodValidator}
 * @param classLoader
 *            the class loader for loading snippet project classes
 */
private void parseIncludedMethods(final SetteIncludeCoverage annotation, final MethodValidator v,
        final ClassLoader classLoader) {
    if (annotation == null) {
        return;
    }

    Class<?>[] includedClasses = annotation.classes();
    String[] includedMethodStrings = annotation.methods();
    boolean shouldParse = true; // only parse if no validation error

    // check the arrays: not empty, no null element, same lengths
    if (ArrayUtils.isEmpty(includedClasses)) {
        v.addException("The included class list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedClasses, null)) {
        v.addException("The included class list " + "must not contain null elements");
        shouldParse = false;
    }

    if (ArrayUtils.isEmpty(includedMethodStrings)) {
        v.addException("The included method list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedMethodStrings, null)) {
        v.addException("The included method list " + "must not contain null elements");
        shouldParse = false;
    }

    if (!ArrayUtils.isSameLength(includedClasses, includedMethodStrings)) {
        v.addException("The included class list and method list " + "must have the same length");
        shouldParse = false;
    }

    if (shouldParse) {
        // check and add methods
        for (int i = 0; i < includedClasses.length; i++) {
            Class<?> includedClass = includedClasses[i];
            String includedMethodString = includedMethodStrings[i].trim();

            if (includedMethodString.equals("*")) {
                // add all non-synthetic constructors
                for (Constructor<?> c : includedClass.getDeclaredConstructors()) {
                    if (!c.isSynthetic()) {
                        addIncludedConstructor(c, v);
                    }
                }
                // add all non-synthetic methods
                for (Method m : includedClass.getDeclaredMethods()) {
                    if (!m.isSynthetic()) {
                        addIncludedMethod(m, v);
                    }
                }
            } else {
                parseIncludedMethod(includedClass, includedMethodString, v, classLoader);
            }
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @param signature/*from w  w  w  . j a  va2 s .  com*/
 *          the signature of {@link Constructor} 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) {
    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:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @param signature//from   w ww.j  a v  a 2s.  co m
 *          the generic signature of {@link Constructor} in same format as
 *          {@link #getConstructorGenericSignature(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> getConstructorByGenericSignature(Class<T> clazz, String signature) {
    Assert.isNotNull(clazz);
    Assert.isNotNull(signature);
    // check all declared constructors
    for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
        if (getConstructorGenericSignature(constructor).equals(signature)) {
            constructor.setAccessible(true);
            return (Constructor<T>) constructor;
        }
    }
    // not found
    return null;
}

From source file:com.vertica.hadoop.VerticaOutputFormat.java

/**
 * Given a class, initializes it and returns it. If the class is a subclass of
 * @{link AbstractVerticaOutputCommitter}, then the constructor that takes a
 * @{link VerticaOutputFormat} object will be used. Alternatively, the class can implement
 * @{link OutputCommitter} directly./*  ww  w.j  a v  a 2  s  .c o  m*/
 * @param outputCommitterClass
 * @param configuration
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private OutputCommitter initializeOutputCommitter(Class outputCommitterClass, Configuration configuration)
        throws IOException {
    // If class extends AbstractVerticaOutputCommitter, create one of those
    // else it needs to be an instance of OutputCommitter
    // else throw exception
    if (AbstractVerticaOutputCommitter.class.isAssignableFrom(outputCommitterClass)) {

        // iterate through the constructors to find the one we're looking for
        for (Constructor constructor : outputCommitterClass.getDeclaredConstructors()) {
            if (constructor.getGenericParameterTypes().length == 1
                    && constructor.getGenericParameterTypes()[0].equals(VerticaOutputFormat.class)) {
                try {
                    return (OutputCommitter) constructor.newInstance(this);
                } catch (Exception e) {
                    throw new IOException("Could not initialize OutputCommitter class "
                            + outputCommitterClass.getCanonicalName(), e);
                }
            }
        }

        throw new IOException("Implementation of AbstractVerticaOutputCommitter must "
                + "have a constructor that takes a VerticaOutputFormat object");
    } else if (OutputCommitter.class.isAssignableFrom(outputCommitterClass)) {
        return (OutputCommitter) ReflectionUtils.newInstance(outputCommitterClass, configuration);
    }

    throw new IOException(String.format("Configured output committer class %s must implement %s",
            outputCommitterClass.getCanonicalName(), OutputCommitter.class.getCanonicalName()));
}

From source file:com.vertica.hivestoragehandler.VerticaOutputFormat.java

/**
 * Given a class, initializes it and returns it. If the class is a subclass of
 * @{link AbstractVerticaOutputCommitter}, then the constructor that takes a
 * @{link VerticaOutputFormat} object will be used. Alternatively, the class can implement
 * @{link OutputCommitter} directly./*  w  w w . jav  a 2 s  . c om*/
 * @param outputCommitterClass
 * @param configuration
 * @return
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private OutputCommitter initializeOutputCommitter(Class outputCommitterClass, Configuration configuration)
        throws IOException {
    // If class extends AbstractVerticaOutputCommitter, create one of those
    // else it needs to be an instance of OutputCommitter
    // else throw exception
    if (VerticaTaskOutputCommitter.class.isAssignableFrom(outputCommitterClass)) {

        // iterate through the constructors to find the one we're looking for
        for (Constructor constructor : outputCommitterClass.getDeclaredConstructors()) {
            if (constructor.getGenericParameterTypes().length == 1
                    && constructor.getGenericParameterTypes()[0].equals(VerticaOutputFormat.class)) {
                try {
                    return (OutputCommitter) constructor.newInstance(this);
                } catch (Exception e) {
                    throw new IOException("Could not initialize OutputCommitter class "
                            + outputCommitterClass.getCanonicalName(), e);
                }
            }
        }

        throw new IOException("Implementation of AbstractVerticaOutputCommitter must "
                + "have a constructor that takes a VerticaOutputFormat object");
    } else if (OutputCommitter.class.isAssignableFrom(outputCommitterClass)) {
        return (OutputCommitter) ReflectionUtils.newInstance(outputCommitterClass, configuration);
    }

    throw new IOException(String.format("Configured output committer class %s must implement %s",
            outputCommitterClass.getCanonicalName(), OutputCommitter.class.getCanonicalName()));
}

From source file:com.mirth.connect.connectors.ws.WebServiceReceiver.java

@Override
public void onStart() throws ConnectorTaskException {
    String channelId = getChannelId();
    String channelName = getChannel().getName();
    String host = replacer.replaceValues(connectorProperties.getListenerConnectorProperties().getHost(),
            channelId, channelName);//from   w  w  w  .  jav  a 2  s  . c o  m
    int port = NumberUtils.toInt(replacer.replaceValues(
            connectorProperties.getListenerConnectorProperties().getPort(), channelId, channelName));

    logger.debug("starting Web Service HTTP server on port: " + port);

    java.util.logging.Logger.getLogger("javax.enterprise.resource.webservices.jaxws.server")
            .setLevel(java.util.logging.Level.OFF);

    try {
        configuration.configureReceiver(this);
        server.bind(new InetSocketAddress(host, port), DEFAULT_BACKLOG);
    } catch (Exception e) {
        throw new ConnectorTaskException("Error creating HTTP Server.", e);
    }

    // TODO: Make a max connections property for this
    int processingThreads = connectorProperties.getSourceConnectorProperties().getProcessingThreads();
    if (processingThreads < 1) {
        processingThreads = 1;
    }

    // Allow more than the channel processing threads so WDSL requests can be accepted even if all processing threads are busy
    executor = Executors.newFixedThreadPool(processingThreads + 4);
    server.setExecutor(executor);
    server.start();

    AcceptMessage acceptMessageWebService = null;

    try {
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds());
        Class<?> clazz = Class.forName(
                replacer.replaceValues(connectorProperties.getClassName(), channelId, channelName), true,
                contextFactory.getApplicationClassLoader());

        if (clazz.getSuperclass().equals(AcceptMessage.class)) {
            Constructor<?>[] constructors = clazz.getDeclaredConstructors();
            for (int i = 0; i < constructors.length; i++) {
                Class<?>[] parameters = constructors[i].getParameterTypes();
                if ((parameters.length == 1) && parameters[0].equals(this.getClass())) {
                    acceptMessageWebService = (AcceptMessage) constructors[i]
                            .newInstance(new Object[] { this });
                }
            }

            if (acceptMessageWebService == null) {
                logger.error(
                        "Custom web service class must implement the constructor: public AcceptMessage(WebServiceReceiver webServiceReceiver)");
            }
        } else {
            logger.error("Custom web service class must extend com.mirth.connect.connectors.ws.AcceptMessage");
        }
    } catch (Exception e) {
        logger.error("Custom web service class initialization failed", e);
    }

    if (acceptMessageWebService == null) {
        logger.error("Custom web service class initialization failed, using DefaultAcceptMessage");
        acceptMessageWebService = new DefaultAcceptMessage(this);
    }

    webServiceEndpoint = Endpoint.create(connectorProperties.getSoapBinding().getValue(),
            acceptMessageWebService);
    Binding binding = webServiceEndpoint.getBinding();
    List<Handler> handlerChain = new LinkedList<Handler>();
    handlerChain.add(new LoggingSOAPHandler(this));
    binding.setHandlerChain(handlerChain);

    String serviceName = replacer.replaceValues(connectorProperties.getServiceName(), channelId, channelName);
    HttpContext context = server.createContext("/services/" + serviceName);

    // Set a security authenticator if needed
    if (authenticatorProvider != null) {
        context.setAuthenticator(createAuthenticator());
    }

    webServiceEndpoint.publish(context);

    eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(),
            ConnectionStatusEventType.IDLE));
}

From source file:org.evosuite.setup.TestClusterGenerator.java

/**
 * Get the set of constructors defined in this class and its superclasses
 * /*from ww w  .j  a va  2  s  .  c om*/
 * @param clazz
 * @return
 */
public static Set<Constructor<?>> getConstructors(Class<?> clazz) {
    Map<String, Constructor<?>> helper = new TreeMap<String, Constructor<?>>();

    Set<Constructor<?>> constructors = new LinkedHashSet<Constructor<?>>();
    try {
        for (Constructor<?> c : clazz.getDeclaredConstructors()) {
            helper.put(org.objectweb.asm.Type.getConstructorDescriptor(c), c);
        }
    } catch (Throwable t) {
        logger.info("Error while analyzing class {}: {}", clazz, t);
    }
    for (Constructor<?> c : helper.values()) {
        constructors.add(c);
    }
    return constructors;
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteria.java

protected List<Member> getSortedMembers(Class<?> currentClass) {
    List<Member> memberList = new ArrayList<Member>();
    for (Class<?> memberType : memberTypes) {
        Member[] members = null;/*from   www .  j  a  va  2s  .c om*/
        if (Constructor.class.equals(memberType)) {
            members = currentClass.getDeclaredConstructors();
        } else if (Method.class.equals(memberType)) {
            members = currentClass.getDeclaredMethods();
        } else if (Field.class.equals(memberType)) {
            members = currentClass.getDeclaredFields();
        }
        if (members != null) {
            List<Member> asList = Arrays.asList(members);
            memberList.addAll(asList);
        }
    }

    Collections.sort(memberList, iterateOrderComparator);
    return memberList;
}