Example usage for java.lang Class newInstance

List of usage examples for java.lang Class newInstance

Introduction

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

Prototype

@CallerSensitive
@Deprecated(since = "9")
public T newInstance() throws InstantiationException, IllegalAccessException 

Source Link

Document

Creates a new instance of the class represented by this Class object.

Usage

From source file:com.amalto.commons.core.utils.xpath.JXPathContextFactory.java

/**
 * Obtain a new instance of a <code>JXPathContextFactory</code>.
 * This static method creates a new factory instance.
 * This method uses the following ordered lookup procedure to determine
 * the <code>JXPathContextFactory</code> implementation class to load:
 * <ul>/*from www.j  av  a2s. co m*/
 * <li>
 * Use  the <code>org.apache.commons.jxpath.JXPathContextFactory</code>
 * system property.
 * </li>
 * <li>
 * Alternatively, use the JAVA_HOME (the parent directory where jdk is
 * installed)/lib/jxpath.properties for a property file that contains the
 * name of the implementation class keyed on
 * <code>org.apache.commons.jxpath.JXPathContextFactory</code>.
 * </li>
 * <li>
 * Use the Services API (as detailed in the JAR specification), if
 * available, to determine the classname. The Services API will look
 * for a classname in the file
 * <code>META- INF/services/<i>org.apache.commons.jxpath.
 * JXPathContextFactory</i></code> in jars available to the runtime.
 * </li>
 * <li>
 * Platform default <code>JXPathContextFactory</code> instance.
 * </li>
 * </ul>
 *
 * Once an application has obtained a reference to a
 * <code>JXPathContextFactory</code> it can use the factory to
 * obtain JXPathContext instances.
 *
 * @return JXPathContextFactory
 * @exception JXPathContextFactoryConfigurationError if the implementation
 *            is not available or cannot be instantiated.
 */
public static JXPathContextFactory newInstance() {
    if (factoryImplName == null) {
        factoryImplName = findFactory(FACTORY_NAME_PROPERTY, DEFAULT_FACTORY_CLASS);
    }

    JXPathContextFactory factoryImpl;
    try {
        Class clazz = Class.forName(factoryImplName);
        factoryImpl = (JXPathContextFactory) clazz.newInstance();
    } catch (ClassNotFoundException cnfe) {
        throw new JXPathContextFactoryConfigurationError(cnfe);
    } catch (IllegalAccessException iae) {
        throw new JXPathContextFactoryConfigurationError(iae);
    } catch (InstantiationException ie) {
        throw new JXPathContextFactoryConfigurationError(ie);
    }
    return factoryImpl;
}

From source file:com.datatorrent.stram.StringCodecs.java

public static <T> void register(final Class<? extends StringCodec<?>> codec, final Class<T> clazz)
        throws InstantiationException, IllegalAccessException {
    check();/* w w w .  j  ava 2  s.com*/
    final StringCodec<?> codecInstance = codec.newInstance();
    ConvertUtils.register(new Converter() {
        @Override
        public Object convert(Class type, Object value) {
            return value == null ? null : codecInstance.fromString(value.toString());
        }

    }, clazz);
    codecs.put(clazz, codec);
}

From source file:ch.cyberduck.core.aquaticprime.LicenseFactory.java

public static License find(final LicenseVerifierCallback callback) {
    try {// w ww .  ja  v  a 2  s .  c o m
        final String clazz = preferences.getProperty("factory.licensefactory.class");
        try {
            final Class<LicenseFactory> name = (Class<LicenseFactory>) Class.forName(clazz);
            final List<License> list = new ArrayList<License>(name.newInstance().open());
            list.removeIf(key -> !key.verify(callback));
            if (list.isEmpty()) {
                return LicenseFactory.EMPTY_LICENSE;
            }
            return list.iterator().next();
        } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
            throw new FactoryException(e.getMessage(), e);
        }
    } catch (AccessDeniedException e) {
        log.warn(String.format("Failure finding receipt %s", e.getMessage()));
    }
    return LicenseFactory.EMPTY_LICENSE;
}

From source file:de.micromata.genome.gwiki.utils.ClassUtils.java

@SuppressWarnings("unchecked")
public static <T> T createDefaultInstance(String className, Class<? extends T> classExpected) {
    try {//  w w w.jav a 2 s .  c o  m
        Class<? extends T> ret = (Class<? extends T>) Class.forName(className, true,
                Thread.currentThread().getContextClassLoader());
        return ret.newInstance();
    } catch (Throwable ex) {
        throw new RuntimeException("Cannot create class instance: " + ex.toString(), ex);
    }
}

From source file:com.moviejukebox.plugin.DatabasePluginController.java

private static MovieDatabasePlugin getMovieDatabasePlugin(String className) {
    try {/*w ww .j  av  a  2s  .co m*/
        Class<? extends MovieDatabasePlugin> pluginClass = Class.forName(className)
                .asSubclass(MovieDatabasePlugin.class);
        return pluginClass.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        LOG.error("Failed instantiating MovieDatabasePlugin: {}", className);
        LOG.error("Default IMDb plugin will be used instead.");
        LOG.error(SystemTools.getStackTrace(ex));
        return new ImdbPlugin();
    }
}

From source file:com.braffdev.server.core.utilities.HandlerClassListInflater.java

/**
 * Instantiates the class the given class config contains.<br />
 * This method checks whether the class is assignable from the given target class.
 *
 * @param classConfig the config./* w ww  . j av  a 2 s . c  o  m*/
 * @param targetClazz the clazz.
 * @return
 */
@SuppressWarnings("unchecked")
private static <T extends Handler> T createInstance(ClassConfig classConfig, Class<T> targetClazz) {

    String clazz = classConfig.getClazz();
    if (StringUtils.isNotBlank(clazz)) {

        try {
            // get class
            Class<?> handlerClass = loadClass(clazz);

            // check if the class is a assignable from the given target class
            if (targetClazz.isAssignableFrom(handlerClass)) {
                return (T) handlerClass.newInstance();

            } else {
                LOGGER.error("The class '" + clazz + "' is unrelated to " + targetClazz + ". Skipping..");
            }

        } catch (Exception e) {
            LOGGER.error(e);
        }
    }

    return null;
}

From source file:com.khubla.cbean.serializer.impl.DefaultClassHasher.java

/**
 * get a class instance//from  ww w. ja v a  2s  .c  om
 */
private static Object getInstance(Class<?> clazz) throws CBeanException {
    try {
        /*
         * instance
         */
        return clazz.newInstance();
    } catch (final Exception e) {
        throw new CBeanException(e);
    }
}

From source file:io.restassured.internal.http.HttpRequestFactory.java

/**
 * Get the HttpRequest class that represents this request type.
 *
 * @return a non-abstract class that implements {@link HttpRequest}
 *//* www .j av  a  2s  . co m*/
static HttpRequestBase createHttpRequest(URI uri, String httpMethod) {
    String method = notNull(upperCase(trimToNull(httpMethod)), "Http method");
    Class<? extends HttpRequestBase> type = HTTP_METHOD_TO_HTTP_REQUEST_TYPE.get(method);
    final HttpRequestBase httpRequest;
    if (type == null) {
        httpRequest = new CustomHttpMethod(method, uri);
    } else {
        try {
            httpRequest = type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        httpRequest.setURI(uri);
    }
    return httpRequest;
}

From source file:com.microsoft.tfs.core.httpclient.auth.AuthPolicy.java

/**
 * Gets the {@link AuthScheme authentication scheme} with the given ID.
 *
 * @param id//  w  w  w . j a v a2  s . c  om
 *        the {@link AuthScheme authentication scheme} ID
 *
 * @return {@link AuthScheme authentication scheme}
 *
 * @throws IllegalStateException
 *         if a scheme with the ID cannot be found
 */
public static synchronized AuthScheme getAuthScheme(final String id) throws IllegalStateException {

    if (id == null) {
        throw new IllegalArgumentException("Id may not be null");
    }
    final Class clazz = (Class) SCHEMES.get(id.toLowerCase());
    if (clazz != null) {
        try {
            return (AuthScheme) clazz.newInstance();
        } catch (final Exception e) {
            LOG.error("Error initializing authentication scheme: " + id, e);
            throw new IllegalStateException(id + " authentication scheme implemented by " + clazz.getName()
                    + " could not be initialized");
        }
    } else {
        throw new IllegalStateException("Unsupported authentication scheme " + id);
    }
}

From source file:Main.java

static Object getInstanceByClass(Class<?> claz) {
    try {/*from www  .  j a  va2  s  . co  m*/
        if (claz == Long.class || claz == Integer.class || claz == Short.class || claz == Double.class
                || claz == Float.class || claz == Byte.class)
            return claz.getConstructor(String.class).newInstance("0");
        else
            return claz.newInstance();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return null;
}