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:mitm.common.security.SecurityFactoryFactory.java

/**
 * Returns the system wide SecurityFactory
 *///  w ww.j ava 2 s.c om
public static synchronized SecurityFactory getSecurityFactory() throws SecurityFactoryFactoryException {
    if (factory == null) {
        try {
            /*
             * Check if a SecurityFactoryBuilder is specified in the system settings
             */
            String builderClazz = System.getProperty(SECURITY_FACTORY_BUILDER_SYSTEM_PROPERTY);

            if (StringUtils.isNotEmpty(builderClazz)) {
                Class<?> builderClass = Class.forName(builderClazz);

                if (!SecurityFactoryBuilder.class.isAssignableFrom(builderClass)) {
                    throw new SecurityFactoryFactoryException(
                            builderClazz + " is-not-a SecurityFactoryBuilder.");
                }

                SecurityFactoryBuilder builder = (SecurityFactoryBuilder) builderClass.newInstance();

                factory = builder.createSecurityFactory();
            } else {
                /*
                 * Use the default security factory
                 */
                factory = new DefaultSecurityFactory();
            }

            logger.info("SecurityFactory instance created. Class: {}", factory.getClass());
        } catch (InstantiationException e) {
            throw new SecurityFactoryFactoryException(e);
        } catch (IllegalAccessException e) {
            throw new SecurityFactoryFactoryException(e);
        } catch (ClassNotFoundException e) {
            throw new SecurityFactoryFactoryException(e);
        }
    }

    return factory;
}

From source file:com.hmsinc.epicenter.classifier.ClassifierFactory.java

/**
 * Creates the actual classifier./* www  .  j a  v a 2s .  c om*/
 * 
 * @param resource
 * @return classificationEngine
 * @throws Exception
 */
private static ClassificationEngine instantiateClassifier(final Resource resource) throws Exception {

    final Unmarshaller u = JAXBContext.newInstance("com.hmsinc.epicenter.classifier.config")
            .createUnmarshaller();

    // Enable validation
    u.setSchema(schema);

    final InputStream is = resource.getInputStream();
    final ClassifierConfig config = (ClassifierConfig) u.unmarshal(is);
    is.close();

    Validate.notNull(config, "Configuration was null!");
    Validate.notNull(config.getImplementation(), "No implementation was specified.");

    final Class<?> implementation = Class.forName(config.getImplementation());
    Validate.isTrue(ClassificationEngine.class.isAssignableFrom(implementation),
            "Implementation must be an instance of ClassificationEngine (was: " + config.getImplementation()
                    + ")");

    final ClassificationEngine engine = (ClassificationEngine) implementation.newInstance();
    engine.init(config);

    return engine;
}

From source file:com.conversantmedia.mapreduce.tool.RunJob.java

/**
 * Runs the tool given the supplied arguments.
 * /*from  w w w. j  a v a  2 s  .co m*/
 * @param args         raw command line arguments
 * @param driverMeta   description of the driver to execute
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected static void runDriver(DriverMeta driverMeta, String[] args) {
    try {

        Configuration config = new Configuration();
        driverMeta.addToConfig(config);

        Class<?> driverClass = driverMeta.driverClass;
        BaseTool driver;
        if (BaseTool.class.isAssignableFrom(driverClass)) {
            driver = (BaseTool) driverClass.newInstance();
        } else {
            driver = new AnnotatedTool(driverClass.newInstance());
            if (driverMeta.listener[0] != Tool.NULLLISTENER.class) {
                for (Class<? extends ToolListener> listenerClass : driverMeta.listener) {
                    ToolListener listener = listenerClass.newInstance();
                    if (Configurable.class.isAssignableFrom(listenerClass)) {
                        ((Configurable) listener).setConf(config);
                    }
                    driver.addListener(new AnnotatedToolListener(listener));
                }
            }
        }

        // Call Hadoops' 'ToolRunner' to kick off this tool
        int res = ToolRunner.run(config, driver, args);
        System.exit(res);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.amalto.core.save.context.SaverContextFactory.java

@SuppressWarnings("unchecked")
static synchronized DocumentSaver invokeSaverExtension(DocumentSaver saver) {
    if (saverExtension == null) {
        try {//from  w w  w  .  j  a  va 2  s.  co  m
            Class<DocumentSaverExtension> extension = (Class<DocumentSaverExtension>) Class
                    .forName("com.amalto.core.save.DocumentSaverExtensionImpl"); //$NON-NLS-1$
            saverExtension = extension.newInstance();
        } catch (ClassNotFoundException e) {
            Logger.getLogger(UserContext.class).warn("No extension found for save."); //$NON-NLS-1$
            saverExtension = new DocumentSaverExtension() {
                public DocumentSaver invokeSaverExtension(DocumentSaver saver) {
                    return saver;
                }
            };
        } catch (Exception e) {
            throw new RuntimeException("Unexpected exception occurred during saver extension lookup."); //$NON-NLS-1$
        }
    }

    return saverExtension.invokeSaverExtension(saver);
}

From source file:edu.mayo.cts2.framework.model.exception.ExceptionFactory.java

/**
 * Creates a new Exception object./*from w w w  . j  ava  2s.  co  m*/
 *
 * @param name the name
 * @param exceptionClazz the exception clazz
 * @return the cts2 rest exception
 */

public static UnknownResourceReference createUnknownResourceException(String name,
        Class<? extends UnknownResourceReference> exceptionClazz) {
    UnknownResourceReference ex;
    try {
        ex = exceptionClazz.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    ex.setSeverity(LoggingLevel.ERROR);
    ex.setCts2Message(ModelUtils.createOpaqueData("Resource with Identifier: " + name + " not found."));

    return ex;
}

From source file:com.rapidminer.operator.generator.ExampleSetGenerator.java

@SuppressWarnings("unchecked")
public static TargetFunction getFunctionForName(String functionName)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {
    for (int i = 0; i < KNOWN_FUNCTION_NAMES.length; i++) {
        if (KNOWN_FUNCTION_NAMES[i].equals(functionName)) {
            return KNOWN_FUNCTION_IMPLEMENTATIONS[i].newInstance();
        }/*from ww w.j a  va  2  s.com*/
    }
    Class<? extends TargetFunction> clazz = (Class<? extends TargetFunction>) Tools.classForName(functionName);
    return clazz.newInstance();
}

From source file:Main.java

public static <T> void resize(List<T> list, int size, Class<T> clazz) {
    if (size == list.size()) {
        return;//from  www . j  av  a2 s .c o m
    }
    if (size < list.size()) {
        Iterator<T> iter = list.iterator();
        for (int i = 1; iter.hasNext(); i++) {
            iter.next();
            if (i > size) {
                iter.remove();
            }
        }
    } else {
        for (int i = 0; i <= size - list.size(); i++) {
            try {
                list.add(clazz != null ? clazz.newInstance() : null);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

From source file:Main.java

private static Object createHash(Class<?> clazz, int size, float loadFactor) {
    // try to use reflection to create the instance
    try {/*from  w w w. j  a  va  2s . com*/
        // use performance parameters
        Constructor<?> c = clazz.getConstructor(int.class, float.class);
        return c.newInstance(calcHashCapacity(size, loadFactor), loadFactor);
    } catch (Exception e) {
        try {
            // try default constructor
            return clazz.newInstance();
        } catch (Exception e2) {
            throw new IllegalArgumentException("clazz=" + clazz);
        }
    }
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * Get Field from obj class or it super class.
 * //from ww  w .  j  a  v  a2 s  .  c  o  m
 * @param obj
 * @param propertyName
 *            may be a nested path, but no indexed/mapped property
 * @return null if not found
 */
public static Field getField(Object obj, String propertyName) {
    int lastIndex = propertyName.lastIndexOf(".");

    // is nested property
    if (lastIndex >= 0) {
        // for example, if obj = user, propertyName = dept.deptName, dept.comp.compName
        // String[] ss = StringUtils.split(propertyName, ".");

        // propertyName = dept.comp.compName, need to get 'dept.comp'
        // propertyName = dept.deptName, need to get 'dept'
        String prop = propertyName.substring(0, lastIndex);
        PropertyDescriptor propPropertyDescriptor = getPropertyDescriptor(obj, prop);
        if (propPropertyDescriptor == null) {
            return null;
        }

        Class<?> propType = propPropertyDescriptor.getPropertyType();
        try {
            Object propObj = propType.newInstance();
            return getFieldForNotNestedProperty(propObj, propertyName.substring(lastIndex + 1));
        } catch (Exception e) {
        }
    }

    return getFieldForNotNestedProperty(obj, propertyName);
}

From source file:jp.co.tis.gsp.tools.dba.dialect.DialectFactory.java

public static Dialect getDialect(String url, String driver) {
    String[] urlTokens = StringUtils.split(url, ':');
    if (urlTokens.length < 3) {
        throw new IllegalArgumentException("url isn't jdbc url format.");
    }/*from   ww  w  .j  av a 2s . c  om*/
    Dialect dialect;
    try {
        Class<?> dialectClass;
        if (classMap.containsKey(urlTokens[1])) {
            dialectClass = classMap.get(urlTokens[1]);

        } else {
            String dialectClassName;
            dialectClassName = "jp.co.tis.gsp.tools.dba.dialect." + StringUtils.capitalize(urlTokens[1])
                    + "Dialect";
            dialectClass = Class.forName(dialectClassName);
        }
        dialect = (Dialect) dialectClass.newInstance();
        dialect.setUrl(url);
        dialect.setDriver(driver);
    } catch (Exception e) {
        throw new IllegalArgumentException("Unsupported Database product:" + urlTokens[1], e);
    }

    return dialect;
}