Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

In this page you can find the example usage for java.lang Class getConstructor.

Prototype

@CallerSensitive
public Constructor<T> getConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

Usage

From source file:edu.purdue.cc.bionet.ui.GraphVisualizer.java

/**
 * Creates a Layout instance from a Class Object.
 * /*from  w w  w.ja v  a 2  s . co m*/
 * @param layout The class object to create the instance of.
 * @param graph The graph to use to instantiate the Layout.
 * @return A new instance of the Layout.
 */
protected static Layout getLayoutInstance(Class<? extends AbstractLayout> layout, Graph graph) {
    try {
        return layout.getConstructor(Graph.class).newInstance(graph);

    } catch (NoSuchMethodException e) {
        Logger.getLogger(GraphVisualizer.class).error(e);
    } catch (InstantiationException e) {
        Logger.getLogger(GraphVisualizer.class).error(e);
    } catch (IllegalAccessException e) {
        Logger.getLogger(GraphVisualizer.class).error(e);
    } catch (java.lang.reflect.InvocationTargetException e) {
        Logger.getLogger(GraphVisualizer.class).error(e);
    }
    return null;
}

From source file:net.padaf.preflight.AbstractValidator.java

/**
 * Instantiate a ValidationHelper using the given class.
 * /*from  www .  j  a  va2  s  .com*/
 * @param avhCls
 * @param cfg
 * @return
 * @throws ValidationException
 */
private AbstractValidationHelper instantiateHelper(Class<? extends AbstractValidationHelper> avhCls,
        ValidatorConfig cfg) throws ValidationException {
    try {
        Constructor<? extends AbstractValidationHelper> construct = avhCls
                .getConstructor(ValidatorConfig.class);
        return construct.newInstance(cfg);
    } catch (NoSuchMethodException e) {
        throw new ValidationException("Unable to create an instance of ValidationHelper : " + e.getMessage(),
                e);
    } catch (InvocationTargetException e) {
        throw new ValidationException("Unable to create an instance of ValidationHelper : " + e.getMessage(),
                e);
    } catch (IllegalAccessException e) {
        throw new ValidationException("Unable to create an instance of ValidationHelper : " + e.getMessage(),
                e);
    } catch (InstantiationException e) {
        throw new ValidationException("Unable to create an instance of ValidationHelper : " + e.getMessage(),
                e);
    }
}

From source file:com.xpn.xwiki.plugin.charts.plots.AreaPlotFactory.java

public Plot create(DataSource dataSource, ChartParams params) throws GenerateException, DataSourceException {
    Class rendererClass = params.getClass(ChartParams.RENDERER);
    if (rendererClass == null || XYItemRenderer.class.isAssignableFrom(rendererClass)) {
        XYItemRenderer renderer;//from  www . j  av  a  2 s  .c om
        if (rendererClass != null) {
            try {
                Constructor ctor = rendererClass.getConstructor(new Class[] {});
                renderer = (XYItemRenderer) ctor.newInstance(new Object[] {});
            } catch (Throwable e) {
                throw new GenerateException(e);
            }
        } else {
            renderer = new XYAreaRenderer();
        }
        ChartCustomizer.customizeXYItemRenderer(renderer, params);

        return XYPlotFactory.getInstance().create(dataSource, renderer, params);
    } else if (CategoryItemRenderer.class.isAssignableFrom(rendererClass)) {
        CategoryItemRenderer renderer;
        if (rendererClass != null) {
            try {
                Constructor ctor = rendererClass.getConstructor(new Class[] {});
                renderer = (CategoryItemRenderer) ctor.newInstance(new Object[] {});
            } catch (Throwable e) {
                throw new GenerateException(e);
            }
        } else {
            renderer = new AreaRenderer();
        }
        ChartCustomizer.customizeCategoryItemRenderer(renderer, params);

        return CategoryPlotFactory.getInstance().create(dataSource, renderer, params);
    } else {
        throw new GenerateException("Incompatible renderer class: " + rendererClass);
    }
}

From source file:PodbaseMetadataMigration2.java

public static <T extends AbstractEntry> List<T> parseFile(File f, Class<T> klass)
        throws IOException, InstantiationException, IllegalAccessException, InvocationTargetException,
        NoSuchMethodException, SecurityException {
    String fileContents = FileUtils.readFileToString(f);
    fileContents = fixFileContents(fileContents);

    List<T> entries = new LinkedList<T>();
    int i = 0;//from www .j a va  2  s  .  c  o  m
    int ignore = 0;
    for (String line : fileContents.split(RECORD_SEPARATOR, -1)) {
        i++;
        if (testMode && i > 10)
            break;
        if (line.trim().length() == 0)
            continue;

        String readable = line.replace(FIELD_SEPARATOR, "[###]");
        if (line.contains("Fatal error")) {
            ignore++;
            //System.out.println(klass.toString()+": Ignoring line "+i+": "+readable);
        }
        try {
            T entry = klass.getConstructor(String.class).newInstance(line);
            entries.add(entry);
        } catch (Exception e) {
            System.out.println(klass.toString() + ": Illegal entry on line " + i + ": " + readable + " ( "
                    + e.getMessage() + ")");
            //e.printStackTrace();
            return entries;
        }
    }
    if (ignore > 0)
        System.out.println("Ignored " + ignore + " entries");

    return entries;
}

From source file:com.eyeq.pivot4j.ui.condition.DefaultConditionFactory.java

/**
 * @see com.eyeq.pivot4j.ui.condition.ConditionFactory#createCondition(java.lang.String)
 *//*from ww w.j a  v  a 2 s. com*/
@Override
public Condition createCondition(String name) {
    if (name == null) {
        throw new NullArgumentException("name");
    }

    Condition condition = null;

    Class<? extends Condition> type = types.get(name);

    if (type != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Instantiating a new condition : " + type);
        }

        try {
            Constructor<? extends Condition> constructor = type.getConstructor(ConditionFactory.class);
            condition = constructor.newInstance(this);
        } catch (Exception e) {
            throw new PivotException(e);
        }
    }

    if (condition == null && logger.isWarnEnabled()) {
        logger.warn("Unknown condition name : " + name);
    }

    return condition;
}

From source file:com.qmetry.qaf.automation.data.ElementInteractor.java

private QAFExtendedWebElement getElement(String loc, Class<? extends QAFExtendedWebElement> eleClass) {

    try {/*  w w  w. j  av a2 s. co  m*/
        Constructor<? extends QAFExtendedWebElement> con = eleClass.getConstructor(String.class);
        con.setAccessible(true);
        QAFExtendedWebElement ele = con.newInstance(loc);
        ele.waitForVisible();
        return ele;
    } catch (Exception e) {
        throw new AutomationError(e);
    }

}

From source file:com.tapas.evidence.fe.form.EvidenceForm.java

private void setupFormFieldFactory(final Model model, final MetaModel metaModel,
        final IUiMessageSource messageSource, final Locale locale) {
    final Class<? extends FormFieldFactory> formFieldFactory = metaModel.getFormFieldFactory();
    if (formFieldFactory != null) {
        try {/*  w w  w. ja  v  a2 s  .c  om*/
            final Constructor<? extends FormFieldFactory> constructor = formFieldFactory
                    .getConstructor(new Class[] { IUiMessageSource.class, Locale.class });
            final EvidenceFormFieldFactory instance = (EvidenceFormFieldFactory) constructor
                    .newInstance(new Object[] { messageSource, locale });
            this.setFormFieldFactory(instance);
        } catch (InstantiationException e) {
            throw new EvidenceFormException("InstantiationException for " + formFieldFactory.getName(), e);
        } catch (IllegalAccessException e) {
            throw new EvidenceFormException("IllegalAccessException for " + formFieldFactory.getName(), e);
        } catch (SecurityException e) {
            throw new EvidenceFormException("SecurityException for " + formFieldFactory.getName(), e);
        } catch (NoSuchMethodException e) {
            throw new EvidenceFormException("NoSuchMethodException for " + formFieldFactory.getName(), e);
        } catch (IllegalArgumentException e) {
            throw new EvidenceFormException("IllegalArgumentException for " + formFieldFactory.getName(), e);
        } catch (InvocationTargetException e) {
            throw new EvidenceFormException("InvocationTargetException for " + formFieldFactory.getName(), e);
        }
    }
}

From source file:com.aurel.track.lucene.LuceneUtil.java

/**
 * Initializes the lucene parameters from the the database 
 * (table TSite, field Preferences)  // www .j ava 2s .  c om
 * @param site
 */
public static void configLuceneParameters(TSiteBean site) {
    //get useLucene 
    String useLuceneStr = site.getUseLucene();
    if (useLuceneStr == null || "".equals(useLuceneStr.trim())) {
        useLuceneStr = "false";
    }
    boolean useLucene = Boolean.valueOf(useLuceneStr).booleanValue();
    LuceneUtil.setUseLucene(useLucene);
    //get indexAttachments
    String indexAttachmentsStr = site.getIndexAttachments();
    if (indexAttachmentsStr == null || "".equals(indexAttachmentsStr.trim())) {
        indexAttachmentsStr = "false";
    }
    boolean indexAttachments = Boolean.valueOf(indexAttachmentsStr).booleanValue();
    LuceneUtil.setIndexAttachments(indexAttachments);
    //get reindexOnStartup
    String reindexOnStartupStr = site.getReindexOnStartup();
    if (reindexOnStartupStr == null || "".equals(reindexOnStartupStr.trim())) {
        reindexOnStartupStr = "false";
    }
    boolean reindexOnStartup = Boolean.valueOf(reindexOnStartupStr).booleanValue();
    LuceneUtil.setReindexOnStartup(reindexOnStartup);
    //get analyzerStr
    String analyzerStr = site.getAnalyzer();
    if (analyzerStr == null || "".equals(analyzerStr.trim())) {
        analyzerStr = StandardAnalyzer.class.getName();
    }
    //get the analyzer class
    Class analyzerClass = null;
    try {
        analyzerClass = Class.forName(analyzerStr.trim());
    } catch (ClassNotFoundException e) {
        LOGGER.error("Analyzer class not found. Fall back to StandardAnalyzer." + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (analyzerClass != null) {
        Class partypes[] = new Class[0];
        Constructor ct = null;
        try {
            ct = analyzerClass.getConstructor(partypes);
        } catch (Exception e) {
            LOGGER.info(
                    "Getting the Version based constructor for " + analyzerStr.trim() + " failed with " + e);
        }
        if (ct != null) {
            //Object arglist[] = new Object[1];
            //arglist[0] = LuceneUtil.VERSION;
            try {
                analyzer = (Analyzer) ct.newInstance(/*arglist*/);
            } catch (Exception e) {
                LOGGER.error("Instanciationg the Version based constructor for " + analyzerStr.trim()
                        + " failed with " + e);
            }
        }
        //then try it with implicit constructor (for earlier lucene versions)
        if (analyzer == null) {
            try {
                analyzer = (Analyzer) analyzerClass.newInstance();
                LOGGER.info("Instantiating the Analyzer through default constructor");
            } catch (Exception e) {
                LOGGER.error(
                        "Instantiating the Analyzer through default constructor failed with " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
    if (analyzer == null) {
        LOGGER.warn("Fall back on creating a StandardAnalyzer instance");
        analyzer = new StandardAnalyzer();
    }
    LuceneUtil.setAnalyzer(analyzer);
    //get indexPath
    String indexPath = site.getIndexPath();
    if (indexPath == null) {
        indexPath = "";
    }
    LuceneUtil.setPath(indexPath);
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultSSLProtocolSocketFactory.java

private void configureSNI(final Socket socket, final String host) {

    if (System.getProperty("java.version").compareTo("1.8") < 0) { //$NON-NLS-1$ //$NON-NLS-2$
        return;/*  ww  w  .j  a  va2  s.c om*/
    }

    /*
     * Classes used to configure Server Name client-hello extension were
     * introduced in Java 8. So, we neither can use nor compile this code
     * using Java 6-7. Thus, let's use reflection.
     */

    try {
        final SSLSocket sslSocket = (SSLSocket) socket;
        final SSLParameters params = sslSocket.getSSLParameters();

        final Class<?> sniHostNameClass = Class.forName("javax.net.ssl.SNIHostName"); //$NON-NLS-1$
        final Constructor<?> sniHostNameClassConstructor = sniHostNameClass.getConstructor(String.class);

        final Object serverName = sniHostNameClassConstructor.newInstance(host);
        final List<Object> serverNames = new ArrayList<Object>(1);
        serverNames.add(serverName);

        final Class<?> paramsClass = params.getClass();
        final Method setServerNames = paramsClass.getMethod("setServerNames", List.class); //$NON-NLS-1$
        setServerNames.invoke(params, serverNames);

        sslSocket.setSSLParameters(params);
    } catch (final Exception e) {
        log.error("Eror configuring SSL socket with SNI cipher extension:", e); //$NON-NLS-1$
    }
}

From source file:com.nearinfinity.blur.thrift.AsyncClientPool.java

private TAsyncClient newClient(Class<?> c, Connection connection) throws InterruptedException {
    BlockingQueue<TAsyncClient> blockingQueue = getQueue(connection);
    TAsyncClient client = blockingQueue.poll();
    if (client != null) {
        return client;
    }//w  w w  . java 2 s. c o m

    AtomicInteger counter;
    synchronized (_numberOfConnections) {
        counter = _numberOfConnections.get(connection.getHost());
        if (counter == null) {
            counter = new AtomicInteger();
            _numberOfConnections.put(connection.getHost(), counter);
        }
    }

    synchronized (counter) {
        int numOfConnections = counter.get();
        while (numOfConnections >= _maxConnectionsPerHost) {
            client = blockingQueue.poll(_pollTime, TimeUnit.MILLISECONDS);
            if (client != null) {
                return client;
            }
            LOG.debug("Waiting for client number of connection [" + numOfConnections
                    + "], max connection per host [" + _maxConnectionsPerHost + "]");
            numOfConnections = counter.get();
        }
        LOG.info("Creating a new client for [" + connection + "]");
        String name = c.getName();
        Constructor<?> constructor = _constructorCache.get(name);
        if (constructor == null) {
            String clientClassName = name.replace("$AsyncIface", "$AsyncClient");
            try {
                Class<?> clazz = Class.forName(clientClassName);
                constructor = clazz.getConstructor(new Class[] { TProtocolFactory.class,
                        TAsyncClientManager.class, TNonblockingTransport.class });
                _constructorCache.put(name, constructor);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        try {
            TNonblockingSocket transport = newTransport(connection);
            client = (TAsyncClient) constructor
                    .newInstance(new Object[] { _protocolFactory, _clientManager, transport });
            client.setTimeout(_timeout);
            counter.incrementAndGet();
            return client;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}