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:de.micromata.genome.gwiki.utils.ClassUtils.java

/**
 * /*  w  w w. j  a  va 2  s  .  c  om*/
 * @param <T>
 * @param cls
 * @param args must have the exact type
 * @return
 */
public static <T> T createInstance(Class<? extends T> cls, Class<?>[] argTypes, Object... args) {
    try {
        Constructor<? extends T> construktur = cls.getConstructor(argTypes);
        return construktur.newInstance(args);
    } catch (Throwable ex) {
        throw new RuntimeException("Cannot instantiate constructor: " + ex.getMessage(), ex);
    }
}

From source file:org.red5.server.api.persistence.PersistenceUtils.java

/**
 * Returns persistence store object class constructor
 * //from   w  ww .j  av  a2 s.  c om
 * @param theClass
 *            Persistence store class
 * @param interfaces
 *            Interfaces that are being implemented by persistence store object class
 * @return Constructor
 * @throws Exception
 */
private static Constructor<?> getPersistenceStoreConstructor(Class<?> theClass, Class<?>[] interfaces)
        throws Exception {
    Constructor<?> constructor = null;
    for (Class<?> interfaceClass : interfaces) {
        try {
            constructor = theClass.getConstructor(new Class[] { interfaceClass });
        } catch (NoSuchMethodException err) {
            // Ignore this error
        }
        if (constructor != null) {
            break;
        }
        constructor = getPersistenceStoreConstructor(theClass, interfaceClass.getInterfaces());
        if (constructor != null) {
            break;
        }
    }
    return constructor;
}

From source file:edu.usc.goffish.gofs.namenode.NameNodeProvider.java

public static IInternalNameNode loadNameNode(Class<? extends IInternalNameNode> type, URI location)
        throws ReflectiveOperationException {
    Constructor<? extends IInternalNameNode> nameNodeConstructor;
    try {// ww w .j  a  v  a 2 s. c o m
        nameNodeConstructor = type.getConstructor(URI.class);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException(type.getName() + " does not have a constructor of the form "
                + type.getSimpleName() + "(" + URI.class.getName() + ")");
    }

    return nameNodeConstructor.newInstance(location);
}

From source file:org.eclipse.virgo.ide.ui.editors.PdeCompatibilityUtil.java

public static IEditorInput createSystemFileEditorInput(File file) {
    if (isEclipse34) {
        Class<?> systemFileEditorInputClass;
        try {/*from w  w w  .  j a v a 2s. c  o m*/
            systemFileEditorInputClass = Class
                    .forName("org.eclipse.pde.internal.ui.editor.SystemFileEditorInput");
            Constructor<?> constructor = systemFileEditorInputClass.getConstructor(File.class);
            return (IEditorInput) constructor.newInstance(file);
        } catch (ClassNotFoundException e) {
            isEclipse34 = false;
        } catch (Throwable e) {
            SpringCore.log(new Status(IStatus.ERROR, ServerIdeUiPlugin.PLUGIN_ID,
                    "Failed to create instance of SystemFileEditorInput"));
            isEclipse34 = false;
        }
    }
    return null;
}

From source file:com.opengamma.util.ReflectionUtils.java

/**
 * Finds a constructor from a Class.//from  w w  w.  j  a va 2s .c o m
 * 
 * @param <T> the type
 * @param type  the type to create, not null
 * @param paramTypes  the parameter types, not null
 * @return the constructor, not null
 * @throws RuntimeException if the class cannot be loaded
 */
public static <T> Constructor<T> findConstructor(final Class<T> type, final Class<?>... paramTypes) {
    try {
        return type.getConstructor(paramTypes);
    } catch (NoSuchMethodException ex) {
        throw new OpenGammaRuntimeException(ex.getMessage(), ex);
    }
}

From source file:Main.java

public static <T> T newInstance(Class<T> type, Class<?>[] argsClass, Object[] argsValues)
        throws InstantiationException, IllegalAccessException {
    T instance = null;/*w  w w  .  j  a  v a  2  s.co  m*/
    try {
        Constructor<T> constructorDef = type.getConstructor(argsClass);
        instance = constructorDef.newInstance(argsValues);
    } catch (SecurityException e) {
        throw new InstantiationException(e.getMessage());
    } catch (NoSuchMethodException e) {
        throw new InstantiationException(e.getMessage());
    } catch (IllegalArgumentException e) {
        throw new InstantiationException(e.getMessage());
    } catch (InvocationTargetException e) {
        throw new InstantiationException(e.getMessage());
    }
    return instance;
}

From source file:TimeLib.java

/**
 * Get a new Date instance of the specified subclass and given long value.
 * @param type the concrete subclass of the Date instance, must be an
 * instance of subclass of java.util.Date
 * @param d the date/time value as a long
 * @return the new Date instance, or null if the class type is not valid
 *///from w ww . j  a  va 2 s .com
public static Date getDate(Class type, long d) {
    try {
        Constructor c = type.getConstructor(new Class[] { long.class });
        return (Date) c.newInstance(new Object[] { new Long(d) });
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:Main.java

@SuppressWarnings("all")
private static boolean setProxyICS(WebView webview, String host, int port) {
    try {//from w  ww.j  a  va 2 s . c om
        Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge");
        Class params[] = new Class[1];
        params[0] = Class.forName("android.net.ProxyProperties");
        Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy", params);

        Class wv = Class.forName("android.webkit.WebView");
        Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");
        Object mWebViewCoreFieldInstance = getFieldValueSafely(mWebViewCoreField, webview);

        Class wvc = Class.forName("android.webkit.WebViewCore");
        Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
        Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldInstance);

        Class bf = Class.forName("android.webkit.BrowserFrame");
        Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge");
        Object sJavaBridge = getFieldValueSafely(sJavaBridgeField, mBrowserFrame);

        Class ppclass = Class.forName("android.net.ProxyProperties");
        Class pparams[] = new Class[3];
        pparams[0] = String.class;
        pparams[1] = int.class;
        pparams[2] = String.class;
        Constructor ppcont = ppclass.getConstructor(pparams);
        updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null));
        Log.d(LOG_TAG, "Setting proxy with 4.0 API successful!");
        return true;
    } catch (Exception ex) {
        Log.e(LOG_TAG, "failed to set HTTP proxy: " + ex);
        return false;
    }
}

From source file:index.IndexUtils.java

/**
 * ??/*from w ww  . ja  v  a2 s .c o m*/
 * @param doc
 * @param entityPath
 * @return
 * @throws ClassNotFoundException
 * @throws java.beans.IntrospectionException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws java.lang.reflect.InvocationTargetException
 * @throws InstantiationException
 * @throws NoSuchMethodException 
 */
public static Object getIndexResult(Document doc, String entityPath)
        throws ClassNotFoundException, IntrospectionException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, InstantiationException, NoSuchMethodException {
    // ??
    Class c2 = Class.forName(entityPath);
    // 
    Object obj = c2.getConstructor(new Class[] {}).newInstance();
    // 
    Field[] fields = c2.getDeclaredFields();
    // ??
    for (Field field : fields) {
        // ??
        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), c2);
        // setget
        Method method = pd.getWriteMethod();
        // 
        method.invoke(obj, new Object[] { doc.get(field.getName()) });
    }
    return obj;
}

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.//from   w ww .j  a  v  a 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;
        }
    }
}