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:org.jamwiki.utils.ResourceUtil.java

/**
 * Given a String representation of a class name (for example, org.jamwiki.db.AnsiDataHandler)
 * return an instance of the class.  The constructor for the class being instantiated must
 * not take any arguments./*from w  ww . j a v  a 2 s. com*/
 *
 * @param className The name of the class being instantiated.
 * @return A Java Object representing an instance of the specified class.
 */
public static Object instantiateClass(String className) {
    if (StringUtils.isBlank(className)) {
        throw new IllegalArgumentException("Cannot call instantiateClass with an empty class name");
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Instantiating class: " + className);
    }
    try {
        Class clazz = ClassUtils.forName(className, ClassUtils.getDefaultClassLoader());
        Class[] parameterTypes = new Class[0];
        Constructor constructor = clazz.getConstructor(parameterTypes);
        Object[] initArgs = new Object[0];
        return constructor.newInstance(initArgs);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Invalid class name specified: " + className, e);
    } catch (NoSuchMethodException e) {
        throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e);
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException("Specified class does not have a valid constructor: " + className, e);
    } catch (InstantiationException e) {
        throw new IllegalStateException("Specified class could not be instantiated: " + className, e);
    }
}

From source file:com.revolsys.util.JavaBeanUtil.java

public static <T> Constructor<T> getConstructor(final Class<T> clazz, final Class<?>... parameterClasses) {
    try {// w  w  w . j a  v  a  2s  . co  m
        return clazz.getConstructor(parameterClasses);
    } catch (final NoSuchMethodException e) {
        return null;
    } catch (final Throwable e) {
        return Exceptions.throwUncheckedException(e);
    }
}

From source file:com.piusvelte.sonet.core.SonetHttpClient.java

protected static DefaultHttpClient getThreadSafeClient(Context context) {
    if (sHttpClient == null) {
        Log.d(TAG, "create http client");
        SocketFactory sf;/* w w  w. j  a v  a  2s. c  o  m*/
        try {
            Class<?> sslSessionCacheClass = Class.forName("android.net.SSLSessionCache");
            Object sslSessionCache = sslSessionCacheClass.getConstructor(Context.class).newInstance(context);
            Method getHttpSocketFactory = Class.forName("android.net.SSLCertificateSocketFactory")
                    .getMethod("getHttpSocketFactory", new Class<?>[] { int.class, sslSessionCacheClass });
            sf = (SocketFactory) getHttpSocketFactory.invoke(null, CONNECTION_TIMEOUT, sslSessionCache);
        } catch (Exception e) {
            Log.e("HttpClientProvider",
                    "Unable to use android.net.SSLCertificateSocketFactory to get a SSL session caching socket factory, falling back to a non-caching socket factory",
                    e);
            sf = SSLSocketFactory.getSocketFactory();
        }
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
        String versionName;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        StringBuilder userAgent = new StringBuilder();
        userAgent.append(context.getPackageName());
        userAgent.append("/");
        userAgent.append(versionName);
        userAgent.append(" (");
        userAgent.append("Linux; U; Android ");
        userAgent.append(Build.VERSION.RELEASE);
        userAgent.append("; ");
        userAgent.append(Locale.getDefault());
        userAgent.append("; ");
        userAgent.append(Build.PRODUCT);
        userAgent.append(")");
        if (HttpProtocolParams.getUserAgent(params) != null) {
            userAgent.append(" ");
            userAgent.append(HttpProtocolParams.getUserAgent(params));
        }
        HttpProtocolParams.setUserAgent(params, userAgent.toString());
        sHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
    }
    return sHttpClient;
}

From source file:com.alibaba.wasp.util.JVMClusterUtil.java

/**
 * Creates a {@link FServerThread}.//from  ww w .  ja v a2  s . c o m
 * Call 'start' on the returned thread to make it run.
 * @param c Configuration to use.
 * @param hrsc Class to create.
 * @param index Used distinguishing the object returned.
 * @throws java.io.IOException
 * @return FServer added.
 */
public static JVMClusterUtil.FServerThread createFServerThread(final Configuration c,
        final Class<? extends FServer> hrsc, final int index) throws IOException {
    FServer server;
    try {
        Constructor<? extends FServer> ctor = hrsc.getConstructor(Configuration.class);
        ctor.setAccessible(true);
        server = ctor.newInstance(c);
    } catch (InvocationTargetException ite) {
        Throwable target = ite.getTargetException();
        throw new RuntimeException("Failed construction of FServer: " + hrsc.toString()
                + ((target.getCause() != null) ? target.getCause().getMessage() : ""), target);
    } catch (Exception e) {
        IOException ioe = new IOException();
        ioe.initCause(e);
        throw ioe;
    }
    return new JVMClusterUtil.FServerThread(server, index);
}

From source file:com.linkedin.drelephant.util.InfoExtractor.java

/**
 * Returns the workflow client instance based on the scheduler name and the workflow url
 * @param scheduler The name of the scheduler
 * @param url The url of the workflow//from w  ww  .  j  a  v  a2 s  .c o  m
 * @return The Workflow cient based on the workflow url
 */
public static WorkflowClient getWorkflowClientInstance(String scheduler, String url) {
    if (!getSchedulersConfiguredForException().contains(scheduler)) {
        throw new RuntimeException(
                String.format("Scheduler %s is not configured for Exception fingerprinting ", scheduler));
    }

    for (SchedulerConfigurationData data : _configuredSchedulers) {
        if (data.getSchedulerName().equals(scheduler)) {
            try {
                String workflowClass = data.getParamMap().get("exception_class");
                Class<?> schedulerClass = Class.forName(workflowClass);
                Object instance = schedulerClass.getConstructor(String.class).newInstance(url);
                if (!(instance instanceof WorkflowClient)) {
                    throw new IllegalArgumentException("Class " + schedulerClass.getName()
                            + " is not an implementation of " + WorkflowClient.class.getName());
                }
                WorkflowClient workflowClient = (WorkflowClient) instance;
                return workflowClient;
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Could not find class " + data.getClassName(), e);
            } catch (InstantiationException e) {
                throw new RuntimeException("Could not instantiate class " + data.getClassName(), e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Could not access constructor for class" + data.getClassName(), e);
            } catch (RuntimeException e) {
                throw new RuntimeException(data.getClassName() + " is not a valid Scheduler class.", e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException("Could not invoke class " + data.getClassName(), e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Could not find constructor for class " + data.getClassName(), e);
            }
        }
    }
    return null;
}

From source file:eu.esdihumboldt.hale.io.geoserver.ResourceBuilder.java

public static <T extends DataStore> ResourceBuilder dataStore(String name, Class<T> dataStoreType) {
    if (dataStoreType == null) {
        throw new IllegalArgumentException("DataStore type not specified");
    }/*from   w ww. jav  a 2 s  .c  o  m*/

    Constructor<T> constructor;
    try {
        // TODO: this code assumes a constructor taking a single String
        // parameter exists
        constructor = dataStoreType.getConstructor(String.class);

        return new ResourceBuilder(constructor.newInstance(name));
    } catch (Exception e) {
        throw new RuntimeException("Cannot instantiate DataStore type: " + dataStoreType.getName());
    }
}

From source file:com.connectsdk.service.config.ServiceConfig.java

@SuppressWarnings("unchecked")
public static ServiceConfig getConfig(JSONObject json) {
    Class<ServiceConfig> newServiceClass;
    try {/*from   www . j  a  v a2s .c o m*/
        newServiceClass = (Class<ServiceConfig>) Class
                .forName(ServiceConfig.class.getPackage().getName() + "." + json.optString(KEY_CLASS));
        Constructor<ServiceConfig> constructor = newServiceClass.getConstructor(JSONObject.class);

        return constructor.newInstance(json);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:hm.binkley.util.XPropsConverter.java

private static <T, E extends Exception> Conversion<T, E> invokeConstructor(final Class<T> token)
        throws NoSuchMethodError {
    try {/*  www  .  jav  a 2s .co  m*/
        final Constructor<T> ctor = token.getConstructor(String.class);
        return value -> {
            try {
                return ctor.newInstance(value);
            } catch (final IllegalAccessException e) {
                final IllegalAccessError x = new IllegalAccessError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            } catch (final InvocationTargetException e) {
                final Throwable root = getRootCause(e);
                final RuntimeException x = new RuntimeException(root);
                x.setStackTrace(root.getStackTrace());
                throw x;
            } catch (final InstantiationException e) {
                final InstantiationError x = new InstantiationError(e.getMessage());
                x.setStackTrace(e.getStackTrace());
                throw x;
            }
        };
    } catch (final NoSuchMethodException ignored) {
        return null;
    }
}

From source file:com.puppycrawl.tools.checkstyle.utils.CommonUtils.java

/**
 * Gets constructor of targetClass./* w w  w .  ja  va2s.  c om*/
 * @param targetClass
 *            from which constructor is returned
 * @param parameterTypes
 *            of constructor
 * @return constructor of targetClass or {@link IllegalStateException} if any exception occurs
 * @see Class#getConstructor(Class[])
 */
public static Constructor<?> getConstructor(Class<?> targetClass, Class<?>... parameterTypes) {
    try {
        return targetClass.getConstructor(parameterTypes);
    } catch (NoSuchMethodException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:com.lenovo.tensorhusky.common.utils.ResourceCalculatorProcessTree.java

/**
 * Create the ResourceCalculatorProcessTree rooted to specified process
 * from the class name and configure it. If class name is null, this method
 * will try and return a process tree plugin available for this system.
 *
 * @param pid   process pid of the root of the process tree
 * @param clazz class-name/* ww  w  .  j  a v a2s .  c o  m*/
 * @param conf  configure the plugin with this.
 * @return ResourceCalculatorProcessTree or null if ResourceCalculatorPluginTree
 * is not available for this system.
 */
public static ResourceCalculatorProcessTree getResourceCalculatorProcessTree(String pid,
        Class<? extends ResourceCalculatorProcessTree> clazz, HuskyConfiguration conf) {

    if (clazz != null) {
        try {
            Constructor<? extends ResourceCalculatorProcessTree> c = clazz.getConstructor(String.class);
            ResourceCalculatorProcessTree rctree = c.newInstance(pid);
            rctree.setConf(conf);
            return rctree;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // No class given, try a os specific class
    if (ProcfsBasedProcessTree.isAvailable()) {
        return new ProcfsBasedProcessTree(pid);
    }
    if (WindowsBasedProcessTree.isAvailable()) {
        return new WindowsBasedProcessTree(pid);
    }

    // Not supported on this system.
    return null;
}