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:hu.sztaki.ilab.bigdata.common.tools.hbase.PerformanceEvaluation.java

long runOneClient(final Class<? extends Test> cmd, final int startRow, final int perClientRunRows,
        final int totalRows, final int rowsPerPut, final Status status) throws IOException {
    status.setStatus("Start " + cmd + " at offset " + startRow + " for " + perClientRunRows + " rows");
    long totalElapsedTime = 0;

    Test t = null;/*from w w w .  ja va 2 s .  c  o m*/
    TestOptions options = new TestOptions(startRow, perClientRunRows, totalRows, getTableDescriptor().getName(),
            rowsPerPut);
    try {
        Constructor<? extends Test> constructor = cmd.getDeclaredConstructor(Configuration.class,
                TestOptions.class, Status.class);
        t = constructor.newInstance(this.conf, options, status);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Invalid command class: " + cmd.getName()
                + ".  It does not provide a constructor as described by"
                + "the javadoc comment.  Available constructors are: "
                + Arrays.toString(cmd.getConstructors()));
    } catch (Exception e) {
        throw new IllegalStateException("Failed to construct command class", e);
    }
    totalElapsedTime = t.test();

    status.setStatus("Finished " + cmd + " in " + totalElapsedTime + "ms at offset " + startRow + " for "
            + perClientRunRows + " rows");
    return totalElapsedTime;
}

From source file:PerformanceEvaluation.java

long runOneClient(final Class<? extends Test> cmd, final int startRow, final int perClientRunRows,
        final int totalRows, boolean flushCommits, boolean writeToWAL, final Status status, final int scanCache)
        throws IOException {
    status.setStatus("Start " + cmd + " at offset " + startRow + " for " + perClientRunRows + " rows");
    long totalElapsedTime = 0;

    Test t = null;//w  ww  .j  a va2s .  co  m
    TestOptions options = new TestOptions(startRow, perClientRunRows, totalRows, getTableDescriptor().getName(),
            flushCommits, writeToWAL, scanCache);
    try {
        Constructor<? extends Test> constructor = cmd.getDeclaredConstructor(Configuration.class,
                TestOptions.class, Status.class);
        t = constructor.newInstance(this.conf, options, status);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Invalid command class: " + cmd.getName()
                + ".  It does not provide a constructor as described by"
                + "the javadoc comment.  Available constructors are: "
                + Arrays.toString(cmd.getConstructors()));
    } catch (Exception e) {
        throw new IllegalStateException("Failed to construct command class", e);
    }
    totalElapsedTime = t.test();

    status.setStatus("Finished " + cmd + " in " + totalElapsedTime + "ms at offset " + startRow + " for "
            + perClientRunRows + " rows");
    return totalElapsedTime;
}

From source file:org.opencms.search.CmsSearchManager.java

/**
 * Returns an analyzer for the given class name.<p>
 * //from w w  w .ja v a2  s. c  om
 * Since Lucene 3.0, many analyzers require a "version" parameter in the constructor and 
 * can not be created by a simple <code>newInstance()</code> call.
 * This method will create analyzers by name for the {@link CmsSearchIndex#LUCENE_VERSION} version.<p>
 * 
 * @param className the class name of the analyzer
 * @param stemmer the optional stemmer parameter required for the snowball analyzer
 * 
 * @return the appropriate lucene analyzer
 * 
 * @throws Exception if something goes wrong
 * 
 * @deprecated The stemmer parameter is used only by the snownall analyzer, which is deprecated in Lucene 3.
 */
@Deprecated
public static Analyzer getAnalyzer(String className, String stemmer) throws Exception {

    Analyzer analyzer = null;
    Class<?> analyzerClass;
    try {
        analyzerClass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        // allow Lucene standard classes to be written in a short form
        analyzerClass = Class.forName(LUCENE_ANALYZER + className);
    }

    // since Lucene 3.0 most analyzers need a "version" parameter and don't support an empty constructor
    if (StandardAnalyzer.class.equals(analyzerClass)) {
        // the Lucene standard analyzer is used
        analyzer = new StandardAnalyzer(CmsSearchIndex.LUCENE_VERSION);
    } else if (CmsGallerySearchAnalyzer.class.equals(analyzerClass)) {
        // OpenCms gallery multiple language analyzer
        analyzer = new CmsGallerySearchAnalyzer(CmsSearchIndex.LUCENE_VERSION);
    } else {
        boolean hasEmpty = false;
        boolean hasVersion = false;
        boolean hasVersionWithString = false;
        // another analyzer is used, check if we find a suitable constructor 
        Constructor<?>[] constructors = analyzerClass.getConstructors();
        for (int i = 0; i < constructors.length; i++) {
            Constructor<?> c = constructors[i];
            Class<?>[] parameters = c.getParameterTypes();
            if (parameters.length == 0) {
                // an empty constructor has been found
                hasEmpty = true;
            }
            if ((parameters.length == 1) && parameters[0].equals(Version.class)) {
                // a constructor with a Lucene version parameter has been found
                hasVersion = true;
            }
            if ((stemmer != null) && (parameters.length == 2) && parameters[0].equals(Version.class)
                    && parameters[1].equals(String.class)) {
                // a constructor with a Lucene version parameter and a String has been found
                hasVersionWithString = true;
            }
        }
        if (hasVersionWithString) {
            // a constructor with a Lucene version parameter and a String has been found
            analyzer = (Analyzer) analyzerClass
                    .getDeclaredConstructor(new Class[] { Version.class, String.class })
                    .newInstance(CmsSearchIndex.LUCENE_VERSION, stemmer);
        } else if (hasVersion) {
            // a constructor with a Lucene version parameter has been found
            analyzer = (Analyzer) analyzerClass.getDeclaredConstructor(new Class[] { Version.class })
                    .newInstance(CmsSearchIndex.LUCENE_VERSION);
        } else if (hasEmpty) {
            // an empty constructor has been found
            analyzer = (Analyzer) analyzerClass.newInstance();
        }
    }
    return analyzer;
}

From source file:org.jvnet.hudson.test.JenkinsRule.java

public Constructor<?> findDataBoundConstructor(Class<?> c) {
    for (Constructor<?> m : c.getConstructors()) {
        if (m.getAnnotation(DataBoundConstructor.class) != null)
            return m;
    }/*from   w  ww .java2 s  . c o  m*/
    return null;
}

From source file:org.apache.solr.core.SolrCore.java

/**
 * Creates an instance by trying a constructor that accepts a SolrCore before
 * trying the default (no arg) constructor.
 *
 * @param className the instance class to create
 * @param cast      the class or interface that the instance should extend or implement
 * @param msg       a message helping compose the exception error if any occurs.
 * @param core      The SolrCore instance for which this object needs to be loaded
 * @return the desired instance/*  w w w  .j  ava  2 s .com*/
 * @throws SolrException if the object could not be instantiated
 */
public static <T> T createInstance(String className, Class<T> cast, String msg, SolrCore core,
        ResourceLoader resourceLoader) {
    Class<? extends T> clazz = null;
    if (msg == null)
        msg = "SolrCore Object";
    try {
        clazz = resourceLoader.findClass(className, cast);
        //most of the classes do not have constructors which takes SolrCore argument. It is recommended to obtain SolrCore by implementing SolrCoreAware.
        // So invariably always it will cause a  NoSuchMethodException. So iterate though the list of available constructors
        Constructor<?>[] cons = clazz.getConstructors();
        for (Constructor<?> con : cons) {
            Class<?>[] types = con.getParameterTypes();
            if (types.length == 1 && types[0] == SolrCore.class) {
                return cast.cast(con.newInstance(core));
            }
        }
        return resourceLoader.newInstance(className, cast);//use the empty constructor
    } catch (SolrException e) {
        throw e;
    } catch (Exception e) {
        // The JVM likes to wrap our helpful SolrExceptions in things like
        // "InvocationTargetException" that have no useful getMessage
        if (null != e.getCause() && e.getCause() instanceof SolrException) {
            SolrException inner = (SolrException) e.getCause();
            throw inner;
        }

        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                "Error Instantiating " + msg + ", " + className + " failed to instantiate " + cast.getName(),
                e);
    }
}

From source file:org.apache.hadoop.hbase.rest.PerformanceEvaluation.java

long runOneClient(final Class<? extends Test> cmd, final int startRow, final int perClientRunRows,
        final int totalRows, boolean flushCommits, boolean writeToWAL, boolean useTags, int noOfTags,
        HConnection connection, final Status status) throws IOException {
    status.setStatus("Start " + cmd + " at offset " + startRow + " for " + perClientRunRows + " rows");
    long totalElapsedTime = 0;

    TestOptions options = new TestOptions(startRow, perClientRunRows, totalRows, N, tableName, flushCommits,
            writeToWAL, useTags, noOfTags, connection);
    final Test t;
    try {// w w  w .  jav  a  2 s  . c o m
        Constructor<? extends Test> constructor = cmd.getDeclaredConstructor(Configuration.class,
                TestOptions.class, Status.class);
        t = constructor.newInstance(this.conf, options, status);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Invalid command class: " + cmd.getName()
                + ".  It does not provide a constructor as described by"
                + "the javadoc comment.  Available constructors are: "
                + Arrays.toString(cmd.getConstructors()));
    } catch (Exception e) {
        throw new IllegalStateException("Failed to construct command class", e);
    }
    totalElapsedTime = t.test();

    status.setStatus("Finished " + cmd + " in " + totalElapsedTime + "ms at offset " + startRow + " for "
            + perClientRunRows + " rows");
    return totalElapsedTime;
}

From source file:com.connexta.arbitro.ConfigurationStore.java

/**
 * Private helper that is used by all the code to load an instance of the given class...this
 * assumes that the class is in the classpath, both for simplicity and for stronger security
 *//*from  w  w  w  .ja v a  2s  .co m*/
private Object loadClass(String prefix, Node root) throws ParsingException {
    // get the name of the class
    String className = root.getAttributes().getNamedItem("class").getNodeValue();

    if (logger.isDebugEnabled()) {
        logger.debug("Loading [ " + prefix + ": " + className + " ]");
    }

    // load the given class using the local classloader
    Class c = null;
    try {
        c = loader.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        throw new ParsingException("couldn't load class " + className, cnfe);
    }
    Object instance = null;

    // figure out if there are any parameters to the constructor
    if (!root.hasChildNodes()) {
        // we're using a null constructor, so this is easy
        try {
            instance = c.newInstance();
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className + " with empty constructor", ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        }
    } else {
        // parse the arguments to the constructor
        Set args = null;
        try {
            args = getArgs(root);
        } catch (IllegalArgumentException iae) {
            throw new ParsingException("illegal class arguments", iae);
        }
        int argLength = args.size();

        // next we need to see if there's a constructor that matches the
        // arguments provided...this has to be done by hand since
        // Class.getConstructor(Class []) doesn't handle sub-classes and
        // generic types (for instance, a constructor taking List won't
        // match a parameter list containing ArrayList)

        // get the list of all available constructors
        Constructor[] cons = c.getConstructors();
        Constructor constructor = null;

        for (int i = 0; i < cons.length; i++) {
            // get the parameters for this constructor
            Class[] params = cons[i].getParameterTypes();
            if (params.length == argLength) {
                Iterator it = args.iterator();
                int j = 0;

                // loop through the parameters and see if each one is
                // assignable from the coresponding input argument
                while (it.hasNext()) {
                    if (!params[j].isAssignableFrom(it.next().getClass()))
                        break;
                    j++;
                }

                // if we looked at all the parameters, then this
                // constructor matches the input
                if (j == argLength)
                    constructor = cons[i];
            }

            // if we've found a matching constructor then stop looping
            if (constructor != null)
                break;
        }

        // make sure we found a matching constructor
        if (constructor == null)
            throw new ParsingException("couldn't find a matching " + "constructor");

        // finally, instantiate the class
        try {
            instance = constructor.newInstance(args.toArray());
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className, ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        } catch (InvocationTargetException ite) {
            throw new ParsingException("couldn't create " + className, ite);
        }
    }

    return instance;
}

From source file:org.wso2.balana.ConfigurationStore.java

/**
 * Private helper that is used by all the code to load an instance of the given class...this
 * assumes that the class is in the classpath, both for simplicity and for stronger security
 *///from  w  ww. j  av  a 2s  .com
private Object loadClass(String prefix, Node root) throws ParsingException {
    // get the name of the class
    String className = root.getAttributes().getNamedItem("class").getNodeValue();

    if (logger.isDebugEnabled()) {
        logger.debug("Loading [ " + prefix + ": " + className + " ]");
    }

    // load the given class using the local classloader
    Class c = null;
    try {
        c = loader.loadClass(className);
    } catch (ClassNotFoundException cnfe) {
        throw new ParsingException("couldn't load class " + className, cnfe);
    }
    Object instance = null;

    // figure out if there are any parameters to the constructor
    if (!root.hasChildNodes()) {
        // we're using a null constructor, so this is easy
        try {
            instance = c.newInstance();
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className + " with empty constructor", ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        }
    } else {
        // parse the arguments to the constructor
        Set<Object> args = null;
        try {
            args = getArgs(root);
        } catch (IllegalArgumentException iae) {
            throw new ParsingException("illegal class arguments", iae);
        }
        int argLength = args.size();

        // next we need to see if there's a constructor that matches the
        // arguments provided...this has to be done by hand since
        // Class.getConstructor(Class []) doesn't handle sub-classes and
        // generic types (for instance, a constructor taking List won't
        // match a parameter list containing ArrayList)

        // get the list of all available constructors
        Constructor[] cons = c.getConstructors();
        Constructor constructor = null;

        for (int i = 0; i < cons.length; i++) {
            // get the parameters for this constructor
            Class[] params = cons[i].getParameterTypes();
            if (params.length == argLength) {
                Iterator it = args.iterator();
                int j = 0;

                // loop through the parameters and see if each one is
                // assignable from the coresponding input argument
                while (it.hasNext()) {
                    if (!params[j].isAssignableFrom(it.next().getClass()))
                        break;
                    j++;
                }

                // if we looked at all the parameters, then this
                // constructor matches the input
                if (j == argLength)
                    constructor = cons[i];
            }

            // if we've found a matching constructor then stop looping
            if (constructor != null)
                break;
        }

        // make sure we found a matching constructor
        if (constructor == null)
            throw new ParsingException("couldn't find a matching " + "constructor");

        // finally, instantiate the class
        try {
            instance = constructor.newInstance(args.toArray());
        } catch (InstantiationException ie) {
            throw new ParsingException("couldn't instantiate " + className, ie);
        } catch (IllegalAccessException iae) {
            throw new ParsingException("couldn't get access to instance " + "of " + className, iae);
        } catch (InvocationTargetException ite) {
            throw new ParsingException("couldn't create " + className, ite);
        }
    }

    return instance;
}

From source file:plugins.tprovoost.Microscopy.MicroManagerForIcy.MMMainFrame.java

@Override
public IAcquisitionEngine2010 getAcquisitionEngine2010() {
    IAcquisitionEngine2010 pipeline = null;
    try {/*from   w  w w . j a  v  a 2s.c  o m*/
        Thread currentThread = Thread.currentThread();
        ClassLoader currentClassLoader = currentThread.getContextClassLoader();
        currentThread.setContextClassLoader(PluginLoader.getLoader());
        Class<?> acquisitionEngine2010Class = ClassUtil.findClass("org.micromanager.AcquisitionEngine2010");
        if (acquisitionEngine2010Class != null) {
            pipeline = (IAcquisitionEngine2010) acquisitionEngine2010Class.getConstructors()[0]
                    .newInstance(this);
        }
        currentThread.setContextClassLoader(currentClassLoader);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoClassDefFoundError e) {
        e.printStackTrace();
    }
    return pipeline;
}