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.sebuilder.interpreter.IO.java

public static StepType getStepTypeOfName(String name) {
    try {/*from  w  ww.  j  a va 2 s.  c o  m*/
        if (!typesMap.containsKey(name)) {
            String className = name.substring(0, 1).toUpperCase() + name.substring(1);
            boolean rawStepType = true;
            if (name.startsWith("assert")) {
                className = className.substring("assert".length());
                rawStepType = false;
            }
            if (name.startsWith("verify")) {
                className = className.substring("verify".length());
                rawStepType = false;
            }
            if (name.startsWith("waitFor")) {
                className = className.substring("waitFor".length());
                rawStepType = false;
            }
            if (name.startsWith("store") && !name.equals("store")) {
                className = className.substring("store".length());
                rawStepType = false;
            }
            try {
                Class c = Class.forName("com.sebuilder.interpreter.steptype." + className);
                try {
                    Object o = c.newInstance();
                    if (name.startsWith("assert")) {
                        typesMap.put(name, new Assert((Getter) o));
                    } else if (name.startsWith("verify")) {
                        typesMap.put(name, new Verify((Getter) o));
                    } else if (name.startsWith("waitFor")) {
                        typesMap.put(name, new WaitFor((Getter) o));
                    } else if (name.startsWith("store") && !name.equals("store")) {
                        typesMap.put(name, new Store((Getter) o));
                    } else {
                        typesMap.put(name, (StepType) o);
                    }
                } catch (InstantiationException ie) {
                    throw new RuntimeException(c.getName() + " could not be instantiated.", ie);
                } catch (IllegalAccessException iae) {
                    throw new RuntimeException(c.getName() + " could not be instantiated.", iae);
                } catch (ClassCastException cce) {
                    throw new RuntimeException(
                            c.getName() + " does not extend " + (rawStepType ? "StepType" : "Getter") + ".",
                            cce);
                }
            } catch (ClassNotFoundException cnfe) {
                throw new RuntimeException(
                        "No implementation class for step type \"" + name + "\" could be found.", cnfe);
            }
        }

        return typesMap.get(name);
    } catch (Exception e) {
        throw new RuntimeException("Step type \"" + name + "\" is not implemented.", e);
    }
}

From source file:com.silverpeas.bootstrap.SilverpeasContextBootStrapper.java

/**
 * Loads all the JAR libraries available in the SILVERPEAS_HOME/repository/lib directory by using
 * our own classloader so that we avoid JBoss loads them with its its asshole VFS.
 *//*from   w w w  . j ava 2 s.c  o m*/
private static void loadExternalJarLibraries() {
    String libPath = System.getenv("SILVERPEAS_HOME") + separatorChar + "repository" + separatorChar + "lib";
    File libDir = new File(libPath);
    File[] jars = libDir.listFiles();
    URL[] jarURLs = new URL[jars.length];
    try {
        for (int i = 0; i < jars.length; i++) {
            jarURLs[i] = jars[i].toURI().toURL();
        }
        addURLs(jarURLs);
        String[] classNames = GeneralPropertiesManager.getString(CLASSES_TO_LOAD).split(",");
        for (String className : classNames) {
            try {
                Class aClass = ClassLoader.getSystemClassLoader().loadClass(className);
                Class<? extends Provider> jceProvider = aClass.asSubclass(Provider.class);
                Security.insertProviderAt(jceProvider.newInstance(), 0);
            } catch (Throwable t) {
                Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE,
                        t.getMessage(), t);
            }
        }
    } catch (Exception ex) {
        Logger.getLogger(SilverpeasContextBootStrapper.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(),
                ex);
    }
}

From source file:io.github.sparta.helpers.reflex.Reflections.java

/**
 * ??/*from  w  w  w  .  ja  v a2s  .  co  m*/
 *
 * @param className 
 * @return 
 */
@SuppressWarnings("rawtypes")
public static Object instance(String className) {
    try {
        Class dialectCls = Class.forName(className);
        return dialectCls.newInstance();
    } catch (ClassNotFoundException e) {
        log.error("", e);
        return null;
    } catch (InstantiationException e) {
        log.error("", e);
        return null;
    } catch (IllegalAccessException e) {
        log.error("", e);
        return null;
    }
}

From source file:org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.java

public static Builder createBuilder(String className) throws AxisFault {
    try {//  w ww  .j  a va2  s  .  c  o  m
        Class c = Class.forName(className);
        Object o = c.newInstance();
        if (o instanceof Builder) {
            return (Builder) o;
        }
    } catch (ClassNotFoundException e) {
        handleException("Builder class not found :" + className, e);
    } catch (IllegalAccessException e) {
        handleException("Cannot initiate Builder class :" + className, e);
    } catch (InstantiationException e) {
        handleException("Cannot initiate Builder class :" + className, e);
    }
    return null;
}

From source file:org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.java

public static MessageFormatter createFormatter(String className) throws AxisFault {
    try {/*from   w ww .  ja v  a 2s .  c  o m*/
        Class c = Class.forName(className);
        Object o = c.newInstance();
        if (o instanceof MessageFormatter) {
            return (MessageFormatter) o;
        }
    } catch (ClassNotFoundException e) {
        handleException("MessageFormatter class not found :" + className, e);
    } catch (IllegalAccessException e) {
        handleException("Cannot initiate MessageFormatter class :" + className, e);
    } catch (InstantiationException e) {
        handleException("Cannot initiate MessageFormatter class :" + className, e);
    }
    return null;
}

From source file:name.ikysil.beanpathdsl.dynamic.DynamicBeanPath.java

/**
 * Continue bean path construction from a bean of specified class.
 *
 * @param <T> type of the bean/*from  w  w w .j a  v  a  2 s.co  m*/
 * @param clazz class of the bean
 * @return instance of the bean class instrumented to capture getters and setters invocations
 */
@SuppressWarnings("unchecked")
public static <T> T expr(Class<T> clazz) {
    try {
        T result;
        if (Modifier.isFinal(clazz.getModifiers())) {
            result = clazz.newInstance();
        } else {
            ProxyFactory pf = new ProxyFactory();
            if (clazz.isInterface()) {
                pf.setSuperclass(Object.class);
                pf.setInterfaces(new Class<?>[] { clazz });
            } else {
                pf.setSuperclass(clazz);
            }
            pf.setFilter(new DefaultMethodFilter());
            result = (T) pf.create(new Class<?>[0], new Object[0], new DefaultMethodHandler(clazz));
        }
        return result;
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new IllegalStateException(String.format("Can't instantiate %s", clazz.getName()), ex);
    }
}

From source file:cn.quickj.Setting.java

private static void loadApplicationConfig() {
    XMLConfiguration config;// w  w  w  .  j  a v  a 2 s  .c  om
    try {
        config = new XMLConfiguration();
        // ??????
        config.setDelimiterParsingDisabled(true);
        String appconfigPath = webRoot + "WEB-INF/appconfig.xml";
        config.load(appconfigPath);
    } catch (Exception e) {
        config = null;
    }
    String className = null;
    if (config != null)
        className = config.getString("class", null);
    if (className != null) {
        try {
            Class<?> clazz = Class.forName(className);
            appconfig = (ApplicationConfig) clazz.newInstance();
            appconfig.init(config);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("?appconfig.xml?!" + e.getCause());
            appconfig = null;
        }
    }
}

From source file:com.textocat.textokit.morph.dictionary.MorphDictionaryAPIFactory.java

private static synchronized void initialize() {
    if (defaultApi != null) {
        return;//w w  w  . j  a  va2 s  . c o m
    }
    log.info("Searching for MorphDictionaryAPI implementations...");
    Set<String> implClassNames = Sets.newHashSet();
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    try {
        for (Resource implDeclRes : resolver
                .getResources("classpath*:META-INF/uima-ext/morph-dictionary-impl.txt")) {
            InputStream is = implDeclRes.getInputStream();
            try {
                String implClassName = IOUtils.toString(is, "UTF-8").trim();
                if (!implClassNames.add(implClassName)) {
                    throw new IllegalStateException(
                            String.format(
                                    "The classpath contains duplicate declaration of implementation '%s'. "
                                            + "Last one has been read from %s.",
                                    implClassName, implDeclRes.getURL()));
                }
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (implClassNames.isEmpty()) {
        throw new IllegalStateException(String.format("Can't find an implementation of MorphDictionaryAPI"));
    }
    if (implClassNames.size() > 1) {
        throw new IllegalStateException(String.format("More than one implementations have been found:\n%s\n"
                + "Adjust the app classpath or get an implementation by ID.", implClassNames));
    }
    String implClassName = implClassNames.iterator().next();
    log.info("Found MorphDictionaryAPI implementation: {}", implClassName);
    try {
        @SuppressWarnings("unchecked")
        Class<? extends MorphDictionaryAPI> implClass = (Class<? extends MorphDictionaryAPI>) Class
                .forName(implClassName);
        defaultApi = implClass.newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can't instantiate the MorphDictionaryAPI implementation", e);
    }
}

From source file:com.nesscomputing.syslog4j.server.SyslogServer.java

public static final SyslogServerIF createInstance(String protocol, SyslogServerConfigIF config)
        throws SyslogRuntimeException {
    if (StringUtils.isBlank(protocol)) {
        throwRuntimeException("Instance protocol cannot be null or empty");
        return null;
    }//from   w  ww. ja va 2 s .c o  m

    if (config == null) {
        throwRuntimeException("SyslogServerConfig cannot be null");
        return null;
    }

    String syslogProtocol = protocol.toLowerCase();

    SyslogServerIF syslogServer = null;

    synchronized (instances) {
        if (instances.containsKey(syslogProtocol)) {
            throwRuntimeException("SyslogServer instance \"" + syslogProtocol + "\" already defined.");
            return null;
        }

        try {
            Class<? extends SyslogServerIF> syslogClass = config.getSyslogServerClass();

            syslogServer = syslogClass.newInstance();

        } catch (ClassCastException cse) {
            throw new SyslogRuntimeException(cse);

        } catch (IllegalAccessException iae) {
            throw new SyslogRuntimeException(iae);

        } catch (InstantiationException ie) {
            throw new SyslogRuntimeException(ie);
        }

        syslogServer.initialize(syslogProtocol, config);

        instances.put(syslogProtocol, syslogServer);
    }

    return syslogServer;
}

From source file:org.jberet.support.io.NoMappingJsonFactoryObjectFactory.java

static void configureInputDecoratorAndOutputDecorator(final JsonFactory jsonFactory,
        final Hashtable<?, ?> environment) throws Exception {
    final Object inputDecorator = environment.get("inputDecorator");
    if (inputDecorator != null) {
        final Class<?> inputDecoratorClass = NoMappingJsonFactoryObjectFactory.class.getClassLoader()
                .loadClass((String) inputDecorator);
        jsonFactory.setInputDecorator((InputDecorator) inputDecoratorClass.newInstance());
    }//from   w  ww  .j a va  2 s .c om

    final Object outputDecorator = environment.get("outputDecorator");
    if (outputDecorator != null) {
        final Class<?> outputDecoratorClass = NoMappingJsonFactoryObjectFactory.class.getClassLoader()
                .loadClass((String) outputDecorator);
        jsonFactory.setOutputDecorator((OutputDecorator) outputDecoratorClass.newInstance());
    }
}