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:EditImage.java

private static Connection getConnected(String drivername, String dbstring, String username, String password)
        throws Exception {
    Class drvClass = Class.forName(drivername);
    DriverManager.registerDriver((Driver) drvClass.newInstance());
    return (DriverManager.getConnection(dbstring, username, password));
}

From source file:com.bstek.dorado.core.el.DefaultExpressionHandler.java

protected synchronized static Object createDoradoExpressionUtilsBean(Map<String, Method> utilMethods)
        throws Exception {
    if (doradoExpressionUtilsBean == null) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass = null;//from  ww w .j  a  va  2  s .  c o m
        try {
            ctClass = pool.get(DORADO_EXPRESSION_UTILS_TYPE);
        } catch (Exception e) {
            // do nothing
        }
        if (ctClass == null) {
            ctClass = pool.makeClass(DORADO_EXPRESSION_UTILS_TYPE);
        }
        for (Map.Entry<String, Method> entry : utilMethods.entrySet()) {
            String name = entry.getKey();
            Method method = entry.getValue();
            int methodIndex = ArrayUtils.indexOf(method.getDeclaringClass().getMethods(), method);

            StringBuffer buf = new StringBuffer();
            StringBuffer args = new StringBuffer();
            buf.append("public ").append("Object").append(' ').append(name).append('(');
            Class<?>[] parameterTypes = method.getParameterTypes();
            for (int i = 0; i < parameterTypes.length; i++) {
                if (i > 0) {
                    buf.append(',');
                    args.append(',');
                }
                buf.append("Object").append(' ').append("p" + i);
                args.append("p" + i);
            }
            buf.append(")");
            if (method.getExceptionTypes().length > 0) {
                buf.append(" throws ");
                int i = 0;
                for (Class<?> exceptionType : method.getExceptionTypes()) {
                    if (i > 0)
                        buf.append(',');
                    buf.append(exceptionType.getName());
                    i++;
                }
            }
            buf.append("{\n").append("return Class.forName(\"" + method.getDeclaringClass().getName())
                    .append("\").getMethods()[").append(methodIndex).append("].invoke(null, new Object[]{")
                    .append(args).append("});").append("\n}");
            CtMethod delegator = CtNewMethod.make(buf.toString(), ctClass);
            delegator.setName(name);
            ctClass.addMethod(delegator);
        }
        Class<?> cl = ctClass.toClass();
        doradoExpressionUtilsBean = cl.newInstance();
    }
    return doradoExpressionUtilsBean;
}

From source file:com.apporiented.hermesftp.PluginManager.java

/**
 * Need to be invoked from the application's main in order to utilize the dynamic class loader.
 * /*from  w  w w .ja  v a  2  s.c o m*/
 * @param mainClassName Main class.
 * @param startMethod Start method that accepts the main arguments.
 * @param args Array of optional arguments
 */
public static void startApplication(String mainClassName, String startMethod, String[] args) {
    try {
        classLoader.update();
        Class<?> clazz = classLoader.loadClass(mainClassName);
        Object instance = clazz.newInstance();
        Method startup = clazz.getMethod(startMethod, new Class[] { (new String[0]).getClass() });
        startup.invoke(instance, new Object[] { args });
    } catch (Exception e) {
        log.error(e, e);
    }
}

From source file:com.cloudera.sqoop.shims.ShimLoader.java

/**
 * Check the current classloader to see if it can load the prescribed
 * class name as an instance of 'xface'. If so, create an instance of
 * the class and return it./*from w w w .  j av  a2  s  .  c  o  m*/
 * @param className the shim class to attempt to instantiate.
 * @param xface the interface it must implement.
 * @return an instance of className.
 */
private static <T> T getShimInstance(String className, Class<T> xface)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Class clazz = Class.forName(className, true, cl);
    return xface.cast(clazz.newInstance());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.ActiveXObject.java

/**
 * This method//w ww  .j av a  2  s.  co m
 * <ol>
 *   <li>instantiates the MSXML (ActiveX) object if requested (<code>XMLDOMDocument</code>,
 *      <code>XMLHTTPRequest</code>, <code>XSLTemplate</code>)
 *   <li>searches the map specified in the <code>WebClient</code> class for the Java object to instantiate based
 *      on the ActiveXObject constructor String
 *   <li>uses <code>ActiveXObjectImpl</code> to initiate Jacob.
 * </ol>
 *
 * @param cx the current context
 * @param args the arguments to the ActiveXObject constructor
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 */
@JsxConstructor
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj,
        final boolean inNewExpr) {
    if (args.length < 1 || args.length > 2) {
        throw Context
                .reportRuntimeError("ActiveXObject Error: constructor must have one or two String parameters.");
    }
    if (args[0] == Context.getUndefinedValue()) {
        throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter is undefined.");
    }
    if (!(args[0] instanceof String)) {
        throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter must be a String.");
    }
    final String activeXName = (String) args[0];

    final WebWindow window = getWindow(ctorObj).getWebWindow();
    final MSXMLActiveXObjectFactory factory = window.getWebClient().getMSXMLActiveXObjectFactory();
    if (factory.supports(activeXName)) {
        final Scriptable scriptable = factory.create(activeXName, window);
        if (scriptable != null) {
            return scriptable;
        }
    }

    final WebClient webClient = getWindow(ctorObj).getWebWindow().getWebClient();
    final Map<String, String> map = webClient.getActiveXObjectMap();
    if (map != null) {
        final String xClassString = map.get(activeXName);
        if (xClassString != null) {
            try {
                final Class<?> xClass = Class.forName(xClassString);
                final Object object = xClass.newInstance();
                return Context.toObject(object, ctorObj);
            } catch (final Exception e) {
                throw Context.reportRuntimeError("ActiveXObject Error: failed instantiating class "
                        + xClassString + " because " + e.getMessage() + ".");
            }
        }
    }
    if (webClient.getOptions().isActiveXNative() && System.getProperty("os.name").contains("Windows")) {
        try {
            return new ActiveXObjectImpl(activeXName);
        } catch (final Exception e) {
            LOG.warn("Error initiating Jacob", e);
        }
    }

    LOG.warn("Automation server can't create object for '" + activeXName + "'.");
    throw Context.reportRuntimeError("Automation server can't create object for '" + activeXName + "'.");
}

From source file:net.solarnetwork.node.util.ClassUtils.java

/**
 * Instantiate a class of a specific interface type.
 * //w  w  w .j a v  a 2 s .c om
 * @param <T>
 *        the desired interface type
 * @param className
 *        the class name that implements the interface
 * @param type
 *        the desired interface
 * @return new instance of the desired type
 */
public static <T> T instantiateClass(String className, Class<T> type) {
    Class<? extends T> clazz = loadClass(className, type);
    try {
        T o = clazz.newInstance();
        return o;
    } catch (Exception e) {
        throw new RuntimeException("Unable to instantiate class [" + className + ']', e);
    }
}

From source file:cz.jirutka.spring.exhandler.support.HttpMessageConverterUtils.java

/**
 * Returns default {@link HttpMessageConverter} instances, i.e.:
 *
 * <ul>//from w w w .ja v a 2  s  . c  o  m
 *     <li>{@linkplain ByteArrayHttpMessageConverter}</li>
 *     <li>{@linkplain StringHttpMessageConverter}</li>
 *     <li>{@linkplain ResourceHttpMessageConverter}</li>
 *     <li>{@linkplain Jaxb2RootElementHttpMessageConverter} (when JAXB is present)</li>
 *     <li>{@linkplain MappingJackson2HttpMessageConverter} (when Jackson 2.x is present)</li>
 *     <li>{@linkplain org.springframework.http.converter.json.MappingJacksonHttpMessageConverter}
 *         (when Jackson 1.x is present and 2.x not)</li>
 * </ul>
 *
 * <p>Note: It does not return all of the default converters defined in Spring, but just thus
 * usable for exception responses.</p>
 */
@SuppressWarnings("deprecation")
public static List<HttpMessageConverter<?>> getDefaultHttpMessageConverters() {

    List<HttpMessageConverter<?>> converters = new ArrayList<>();

    StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    stringConverter.setWriteAcceptCharset(false); // See SPR-7316

    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(stringConverter);
    converters.add(new ResourceHttpMessageConverter());

    if (isJaxb2Present()) {
        converters.add(new Jaxb2RootElementHttpMessageConverter());
    }
    if (isJackson2Present()) {
        converters.add(new MappingJackson2HttpMessageConverter());

    } else if (isJacksonPresent()) {
        try {
            Class<?> clazz = Class
                    .forName("org.springframework.http.converter.json.MappingJacksonHttpMessageConverter");
            converters.add((HttpMessageConverter<?>) clazz.newInstance());

        } catch (ClassNotFoundException ex) {
            // Ignore it, this class is not available since Spring 4.1.0.
        } catch (InstantiationException | IllegalAccessException ex) {
            throw new IllegalStateException(ex);
        }
    }
    return converters;
}

From source file:MultiMap.java

/**
 * /*from  ww w. j  a va  2s . c  om*/
 * Invokes the Class.newInstance() method on the given Class.
 * 
 * @param theClass
 *            The type to instantiate.
 * 
 * @return An object of the given type, created with the default
 *         constructor. A RuntimeException is thrown if the object could not
 *         be created.
 * 
 */
public static Object newInstance(Class theClass) {
    try {
        return theClass.newInstance();
    }

    catch (InstantiationException error) {
        Object[] filler = { theClass };
        String message = "ObjectCreationFailed";
        throw new RuntimeException(message);
    }

    catch (IllegalAccessException error) {
        Object[] filler = { theClass };
        String message = "DefaultConstructorHidden";
        throw new RuntimeException(message);
    }
}

From source file:com.conwet.silbops.model.AbstractMapping.java

/**
 * Convert attribute-value mapping from its JSON representation.
 *
 * @param clazz the Class of the new type to instantiate
 * @param json JSON representation of a mapping between attributes and values
 * @return the new instance created//from w  ww. jav a 2 s .c  o  m
 * @throws IllegalArgumentException if some problem occur parsing JSON or
 * when creating instance class
 */
@SuppressWarnings("unchecked")
protected static <U extends AbstractMapping<U>> U fromJSON(Class<U> clazz, JSONObject json) {

    try {
        U instance = clazz.newInstance();

        for (Entry<String, Object> entry : (Set<Entry<String, Object>>) json.entrySet()) {

            instance.attribute(Attribute.fromJSON(entry.getKey()), Value.fromJSON(entry.getValue()));
        }

        return instance;
    } catch (InstantiationException | IllegalAccessException ex) {
        throw new IllegalArgumentException("Unable to load instance of class " + clazz, ex);
    }
}

From source file:com.jcraft.weirdx.Extension.java

static void load(String name) {
    try {/*from   w  ww  .j a  v a 2 s.  c  o  m*/
        Class<?> c = Class.forName("com.jcraft.weirdx." + name + "Extension");
        Extension e = (Extension) c.newInstance();
        currentMaxType++;
        e.type = currentMaxType;
        currentMaxEventType++;
        e.eventbase = currentMaxEventType;
        currentMaxEventType += (e.eventcount - 1);
        currentMaxErrorType++;
        e.errorbase = currentMaxErrorType;
        currentMaxErrorType += (e.errorcount - 1);
        for (int i = 0; i < ext.length; i++) {
            if (ext[i] == null) {
                ext[i] = e;
                return;
            }
        }
        Extension[] foo = new Extension[ext.length * 2];
        System.arraycopy(ext, 0, foo, 0, ext.length);
        foo[ext.length] = e;
        ext = foo;
    } catch (Exception e) {
        LOG.error(e);
    }
}