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.nesscomputing.syslog4j.Syslog.java

/**
 * Use createInstance(protocol,config) to create your own Syslog instance.
 *
 * <p>First, create an implementation of SyslogConfigIF, such as UdpNetSyslogConfig.</p>
 *
 * <p>Second, configure that configuration instance.</p>
 *
 * <p>Third, call createInstance(protocol,config) using a short &amp; simple
 * String for the protocol argument.</p>
 *
 * <p>Fourth, either use the returned instance of SyslogIF, or in later code
 * call getInstance(protocol) with the protocol chosen in the previous step.</p>
 *
 * @param protocol/* w  w  w. j  av  a  2  s.  co  m*/
 * @param config
 * @return Returns an instance of SyslogIF.
 * @throws SyslogRuntimeException
 */
public static SyslogIF createInstance(String protocol, SyslogConfigIF config) throws SyslogRuntimeException {
    Preconditions.checkArgument(!StringUtils.isBlank(protocol), "Instance protocol cannot be null or empty");
    Preconditions.checkArgument(config != null, "SyslogConfig cannot be null");

    String syslogProtocol = protocol.toLowerCase();

    SyslogIF syslog = null;

    synchronized (instances) {
        Preconditions.checkState(!instances.containsKey(syslogProtocol),
                "Syslog protocol \"%s\" already defined", protocol);

        try {
            Class<? extends SyslogIF> syslogClass = config.getSyslogClass();
            syslog = syslogClass.newInstance();

        } catch (ClassCastException cse) {
            if (!config.isThrowExceptionOnInitialize()) {
                throw new SyslogRuntimeException(cse);

            } else {
                return null;
            }

        } catch (IllegalAccessException iae) {
            if (!config.isThrowExceptionOnInitialize()) {
                throw new SyslogRuntimeException(iae);

            } else {
                return null;
            }

        } catch (InstantiationException ie) {
            if (!config.isThrowExceptionOnInitialize()) {
                throw new SyslogRuntimeException(ie);

            } else {
                return null;
            }
        }

        syslog.initialize(syslogProtocol, config);

        instances.put(syslogProtocol, syslog);
    }

    return syslog;
}

From source file:kina.utils.Utils.java

/**
 * Creates a new instance of the given class.
 *
 * @param clazz the class object for which a new instance should be created.
 * @return the new instance of class clazz.
 *///  w ww . jav  a  2s .  co m
public static <T extends KinaType> T newTypeInstance(Class<T> clazz) {
    try {
        return clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new GenericException(e);
    }
}

From source file:gdt.data.entity.BaseHandler.java

/**
 * Execute an action//ww  w. j  ava 2s .co  m
 *  @param entigrator instance of  the Entigrator class
 *  @param locator$ the arguments string.
 * @return response string.
 */

public static String execute(Entigrator entigrator, String locator$) {
    try {
        Properties locator = Locator.toProperties(locator$);
        String handlerClass$ = locator.getProperty(HANDLER_CLASS);
        String method$ = locator.getProperty(HANDLER_METHOD);
        Class<?> cls = Class.forName(handlerClass$);
        Object obj = cls.newInstance();
        // System.out.println("ConsoleHandler:execute:context="+handlerClass$);
        Method method = cls.getDeclaredMethod(method$, Entigrator.class, String.class);
        return (String) method.invoke(obj, entigrator, locator$);
    } catch (Exception e) {
        Logger.getLogger(BaseHandler.class.getName()).severe(e.toString());
        return Locator.append(locator$, FacetHandler.METHOD_STATUS, FacetHandler.METHOD_STATUS_FAILED);
    }

}

From source file:com.googlecode.jsfFlex.myFaces.ClassUtils.java

public static Object newInstance(Class clazz) throws FacesException {
    try {/*w  w w  .j  av a  2  s  .  c  o  m*/
        return clazz.newInstance();
    } catch (NoClassDefFoundError e) {
        log.error("Class : " + clazz.getName() + " not found.", e);
        throw new FacesException(e);
    } catch (InstantiationException e) {
        log.error(e.getMessage(), e);
        throw new FacesException(e);
    } catch (IllegalAccessException e) {
        log.error(e.getMessage(), e);
        throw new FacesException(e);
    }
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloader.java

public static Object create(BundleContext bundleContext, String className, List<Object> arguments)
        throws KettlePluginException, ClassNotFoundException, IllegalAccessException, InstantiationException,
        InvocationTargetException {
    ShimBridgingClassloader shimBridgingClassloader = new ShimBridgingClassloader(pluginClassloaderGetter
            .getPluginClassloader(LifecyclePluginType.class.getCanonicalName(), HADOOP_SPOON_PLUGIN),
            bundleContext);/*from  www.  j  av  a  2 s. c  o m*/
    Class<?> clazz = Class.forName(className, true, shimBridgingClassloader);
    if (arguments == null || arguments.size() == 0) {
        return clazz.newInstance();
    }
    for (Constructor<?> constructor : clazz.getConstructors()) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == arguments.size()) {
            boolean match = true;
            for (int i = 0; i < parameterTypes.length; i++) {
                Object o = arguments.get(i);
                if (o != null && !parameterTypes[i].isInstance(o)) {
                    match = false;
                    break;
                }
            }
            if (match) {
                return constructor.newInstance(arguments.toArray());
            }
        }
    }
    throw new InstantiationException(
            "Unable to find constructor for class " + className + " with arguments " + arguments);
}

From source file:com.ts.db.connector.ConnectorDriverManager.java

private static Driver getDriver(File jar, String url, ClassLoader cl) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {/* w  ww .j  a  v a  2  s  . co  m*/
        for (ZipEntry entry : Iteration.asIterable(zipFile.entries())) {
            final String name = entry.getName();
            if (name.endsWith(".class")) {
                final String fqcn = name.replaceFirst("\\.class", "").replace('/', '.');
                try {
                    Class<?> c = DynamicLoader.loadClass(fqcn, cl);
                    if (Driver.class.isAssignableFrom(c)) {
                        Driver driver = (Driver) c.newInstance();
                        if (driver.acceptsURL(url)) {
                            return driver;
                        }
                    }
                } catch (Exception ex) {
                    if (log.isTraceEnabled()) {
                        log.trace(ex.toString());
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
    return null;
}

From source file:hu.ppke.itk.nlpg.purepos.cli.PurePos.java

/**
 * Loads the latest Humor jar file and create an analyzer instance
 * /*from   w ww  .ja v a 2 s. co m*/
 * @return analyzer instance
 */
protected static IMorphologicalAnalyzer loadHumor()
        throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException {
    String humorPath = System.getProperty("humor.path");
    if (humorPath == null)
        throw new ClassNotFoundException("Humor jar file is not present");

    File dir = new File(humorPath);

    File[] candidates = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".jar") && filename.startsWith("humor-");
        }
    });

    Arrays.sort(candidates);

    @SuppressWarnings("deprecation")
    URL humorURL = candidates[candidates.length - 1].toURL();

    URLClassLoader myLoader = new URLClassLoader(new URL[] { humorURL }, PurePos.class.getClassLoader());
    Class<?> humorClass = Class.forName("hu.ppke.itk.nlpg.purepos.morphology.HumorAnalyzer", true, myLoader);
    return (IMorphologicalAnalyzer) humorClass.newInstance();
}

From source file:Main.java

private static int getSmartBarHeight(Activity activity) {
    ActionBar actionbar = activity.getActionBar();
    if (actionbar != null)
        try {/*w w  w . j av  a 2s  . c o  m*/
            Class c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("mz_action_button_min_height");
            int height = Integer.parseInt(field.get(obj).toString());
            return activity.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
            actionbar.getHeight();
        }
    return 0;
}

From source file:com.ultrapower.eoms.common.plugin.ecside.core.TableModelUtils.java

public static Messages getMessages(TableModel model) {
    String messages = model.getPreferences().getPreference(PreferencesConstants.MESSAGES);
    try {//from  w  w  w.  j a  va2  s.c  o  m
        Class classDefinition = Class.forName(messages);
        return (Messages) classDefinition.newInstance();

    } catch (Exception e) {
        String msg = "Could not create the messages [" + messages + "]. The class was not found or does not exist.";
        logger.error(msg, e);
        throw new IllegalStateException(msg);
    }
}

From source file:com.googlecode.jtiger.modules.ecside.core.TableModelUtils.java

public static Messages getMessages(TableModel model) {
    String messages = model.getPreferences().getPreference(PreferencesConstants.MESSAGES);
    try {//from  w  w w.ja v a  2s .c  om
        Class classDefinition = Class.forName(messages);
        return (Messages) classDefinition.newInstance();

    } catch (Exception e) {
        String msg = "Could not create the messages [" + messages
                + "]. The class was not found or does not exist.";
        logger.error(msg, e);
        throw new IllegalStateException(msg);
    }
}