Example usage for java.lang.reflect Constructor newInstance

List of usage examples for java.lang.reflect Constructor newInstance

Introduction

In this page you can find the example usage for java.lang.reflect Constructor newInstance.

Prototype

@CallerSensitive
@ForceInline 
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException 

Source Link

Document

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

Usage

From source file:com.adaptris.core.fs.FsHelper.java

public static FileFilter createFilter(String filterExpression, String filterImpl) throws Exception {
    FileFilter result = null;/*  w w  w  .jav  a  2  s  .  c  om*/
    if (isEmpty(filterExpression)) {
        result = new NoOpFileFilter();
    } else {
        Class[] paramTypes = { filterExpression.getClass() };
        Object[] args = { filterExpression };
        Class c = Class.forName(filterImpl);
        Constructor cnst = c.getDeclaredConstructor(paramTypes);
        result = (FileFilter) cnst.newInstance(args);
    }
    return logWarningIfRequired(result);
}

From source file:com.mobiperf.util.MeasurementJsonConvertor.java

public static MeasurementTask makeMeasurementTaskFromJson(JSONObject json, Context context)
        throws IllegalArgumentException {
    try {/* w  w w.  j  av  a  2s .com*/
        String type = String.valueOf(json.getString("type"));
        Class taskClass = MeasurementTask.getTaskClassForMeasurement(type);
        Method getDescMethod = taskClass.getMethod("getDescClass");
        // The getDescClassForMeasurement() is static and takes no arguments
        Class descClass = (Class) getDescMethod.invoke(null, (Object[]) null);
        MeasurementDesc measurementDesc = (MeasurementDesc) gson.fromJson(json.toString(), descClass);
        Object[] cstParams = { measurementDesc, context };
        Constructor<MeasurementTask> constructor = taskClass.getConstructor(MeasurementDesc.class,
                Context.class);
        return constructor.newInstance(cstParams);
    } catch (JSONException e) {
        throw new IllegalArgumentException(e);
    } catch (SecurityException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalArgumentException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        Logger.w(e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
        Logger.w(e.toString());
        throw new IllegalArgumentException(e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.preprocessors.utils.ProcessDataGetterN3Utils.java

private static ProcessDataGetterN3 instantiateClass(String processorClass, JSONObject jsonObject) {
    ProcessDataGetterN3 pn = null;/*w  w w . j a v  a 2s  .  co  m*/
    try {
        Class<?> clz = Class.forName(processorClass);
        Constructor<?>[] ctList = clz.getConstructors();
        for (Constructor<?> ct : ctList) {
            Class<?>[] parameterTypes = ct.getParameterTypes();
            if (parameterTypes.length > 0 && parameterTypes[0].isAssignableFrom(jsonObject.getClass())) {
                pn = (ProcessDataGetterN3) ct.newInstance(jsonObject);
            } else {
                pn = (ProcessDataGetterN3) ct.newInstance();
            }
        }

    } catch (Exception ex) {
        log.error("Error occurred instantiating " + processorClass, ex);
    }
    return pn;

}

From source file:libepg.epg.section.SectionBodyTest.java

private static final SectionBody init(Object[] args) throws NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    SectionBody target;/*from   w w w.ja v  a  2s  .  com*/
    Class<?>[] params = { TABLE_ID.class, byte[].class };
    Constructor<SectionBody> constructor = SectionBody.class.getDeclaredConstructor(params);
    constructor.setAccessible(true);
    target = constructor.newInstance(args);
    return target;
}

From source file:it.doqui.index.ecmengine.client.backoffice.EcmEngineBackofficeDelegateFactory.java

private static EcmEngineBackofficeDelegate getClassInstance(String ecmEngineBkoDelegateImplName, Log logger)
        throws EcmEngineBackofficeDelegateInstantiationException {
    EcmEngineBackofficeDelegate classInstance = null;

    logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] BEGIN");
    try {/*from ww  w.  ja v  a2  s.c om*/
        logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "Caricamento classe: "
                + ecmEngineBkoDelegateImplName);
        final Class delegateClass = Class.forName(ecmEngineBkoDelegateImplName);
        final Constructor constructor = delegateClass.getConstructor(new Class[] { Log.class });
        classInstance = (EcmEngineBackofficeDelegate) constructor.newInstance(new Object[] { logger });
    } catch (ClassNotFoundException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: classe non trovata.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Classe non trovata.", e);
    } catch (NoSuchMethodException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] "
                + "FATAL: nessun costruttore compatibile.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Nessun costruttore compatibile.", e);
    } catch (InstantiationException e) {
        logger.error(
                "[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: errore di istanziazione.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Errore di istanziazione.", e);
    } catch (IllegalAccessException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] " + "FATAL: errore di accesso.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Errore di accesso.", e);
    } catch (InvocationTargetException e) {
        logger.error("[EcmEngineBackofficeDelegateFactory::getClassInstance] "
                + "FATAL: eccezione nel target invocato.");
        throw new EcmEngineBackofficeDelegateInstantiationException("Eccezione nel target invocato.", e);
    } finally {
        logger.debug("[EcmEngineBackofficeDelegateFactory::getClassInstance] END");
    }
    return classInstance;
}

From source file:com.google.wireless.speed.speedometer.util.MeasurementJsonConvertor.java

@SuppressWarnings("unchecked")
public static MeasurementTask makeMeasurementTaskFromJson(JSONObject json, Context context)
        throws IllegalArgumentException {
    try {//from w  ww  . j  a  v a 2s .  c om
        String type = String.valueOf(json.getString("type"));
        Class taskClass = MeasurementTask.getTaskClassForMeasurement(type);
        Method getDescMethod = taskClass.getMethod("getDescClass");
        // The getDescClassForMeasurement() is static and takes no arguments
        Class descClass = (Class) getDescMethod.invoke(null, (Object[]) null);
        MeasurementDesc measurementDesc = gson.fromJson(json.toString(), descClass);
        Object[] cstParams = { measurementDesc, context };
        Constructor<MeasurementTask> constructor = taskClass.getConstructor(MeasurementDesc.class,
                Context.class);
        return constructor.newInstance(cstParams);
    } catch (JSONException e) {
        throw new IllegalArgumentException(e);
    } catch (SecurityException e) {
        Log.w(SpeedometerApp.TAG, e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (NoSuchMethodException e) {
        Log.w(SpeedometerApp.TAG, e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalArgumentException e) {
        Log.w(SpeedometerApp.TAG, e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        Log.w(SpeedometerApp.TAG, e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        Log.w(SpeedometerApp.TAG, e.getMessage());
        throw new IllegalArgumentException(e);
    } catch (InvocationTargetException e) {
        Log.w(SpeedometerApp.TAG, e.toString());
        throw new IllegalArgumentException(e);
    }
}

From source file:it.cnr.icar.eric.common.security.X509Parser.java

/**
 * Parses a X509Certificate from a DER formatted input stream. Uses the 
 * BouncyCastle provider if available.//  w  w w .java  2 s.c  o m
 *
 * @param inStream The DER InputStream with the certificate.
 * @return X509Certificate parsed from stream.
 * @throws JAXRException in case of IOException or CertificateException
 *  while parsing the stream.
 */
public static X509Certificate parseX509Certificate(InputStream inStream) throws JAXRException {
    try {
        //possible options
        // - der x509 generated by keytool -export
        // - der x509 generated by openssh x509 (might require BC provider)

        // Get the CertificateFactory to parse the stream
        // if BouncyCastle provider available, use it
        CertificateFactory cf;
        try {
            Class<?> clazz = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
            Constructor<?> constructor = clazz.getConstructor(new Class[] {});
            Provider bcProvider = (Provider) constructor.newInstance(new Object[] {});
            Security.addProvider(bcProvider);
            cf = CertificateFactory.getInstance("X.509", "BC");
        } catch (Exception e) {
            // log error if bc present but failed to instanciate/add provider
            if (!(e instanceof ClassNotFoundException)) {
                log.error(CommonResourceBundle.getInstance()
                        .getString("message.FailedToInstantiateBouncyCastleProvider"));
            }
            // fall back to default provider
            cf = CertificateFactory.getInstance("X.509");
        }

        // Read the stream to a local variable
        DataInputStream dis = new DataInputStream(inStream);
        byte[] bytes = new byte[dis.available()];
        dis.readFully(bytes);
        ByteArrayInputStream certStream = new ByteArrayInputStream(bytes);

        // Parse the cert stream
        int i = 0;
        Collection<? extends Certificate> c = cf.generateCertificates(certStream);
        X509Certificate[] certs = new X509Certificate[c.toArray().length];
        for (Iterator<? extends Certificate> it = c.iterator(); it.hasNext();) {
            certs[i++] = (X509Certificate) it.next();
        }

        // Some logging..
        if (log.isDebugEnabled()) {
            if (c.size() == 1) {
                log.debug("One certificate, no chain.");
            } else {
                log.debug("Certificate chain length: " + c.size());
            }
            log.debug("Subject DN: " + certs[0].getSubjectDN().getName());
            log.debug("Issuer DN: " + certs[0].getIssuerDN().getName());
        }

        // Do we need to return the chain?
        // do we need to verify if cert is self signed / valid?
        return certs[0];
    } catch (CertificateException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } catch (IOException e) {
        String msg = CommonResourceBundle.getInstance().getString("message.parseX509CertificateStreamFailed",
                new Object[] { e.getClass().getName(), e.getMessage() });
        throw new JAXRException(msg, e);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
            inStream = null;
        }
    }
}

From source file:lite.flow.runtime.kiss.ComponentUtil.java

public static Object newInstance(Component component, FlowExecutionContext executionContext)
        throws ReflectiveOperationException {

    Class<?> componentClazz = component.componentClazz;
    Map<String, Object> resources = executionContext.getResources();
    Map<String, Object> parameters = component.parameters;

    Constructor<?> constructor = pickConstructor(componentClazz, resources, parameters);
    Object args[] = buildConstructorArgs(constructor, resources, parameters);

    Object componentInstance = constructor.newInstance(args);

    return componentInstance;
}

From source file:info.novatec.testit.livingdoc.util.ClassUtils.java

public static <T> T invoke(Constructor<T> constructor, Object... args) throws Throwable {
    try {/*from  www. ja  v a 2  s .  co  m*/
        return constructor.newInstance(args);
    } catch (InstantiationException e) {
        throw e.getCause();
    }
}

From source file:com.auth10.federation.FederatedConfiguration.java

private static IFederatedConfiguration load(HttpServletRequest request) {
    java.util.Properties props = new java.util.Properties();
    IFederatedConfiguration configurator = null;
    try {/*from w  w  w.  j a va 2  s  . c o  m*/
        InputStream is = FederatedConfiguration.class.getResourceAsStream("/federation.properties");
        props.load(is);
        String className = props.getProperty(LOADER_CLASS, "com.auth10.federation.BasicFileConfiguration");
        if (!StringUtils.isEmpty(className)) {
            Constructor<?> declaredConstructor = Class.forName(className)
                    .getDeclaredConstructor(HttpServletRequest.class);
            configurator = (IFederatedConfiguration) declaredConstructor.newInstance(request);
        }

    } catch (IOException e) {
        throw new RuntimeException("Configuration could not be loaded", e);
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*
    if (configurator == null){
    //Utilizamos los valores por defecto
    configurator = new BasicFileConfiguration(request);
    }
    */

    return configurator;
}