Example usage for java.lang ClassLoader loadClass

List of usage examples for java.lang ClassLoader loadClass

Introduction

In this page you can find the example usage for java.lang ClassLoader loadClass.

Prototype

public Class<?> loadClass(String name) throws ClassNotFoundException 

Source Link

Document

Loads the class with the specified binary name.

Usage

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
public void enumWithExtendedCharacters() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/enum/enumWithExtendedCharacters.json", "com.example");

    resultsClassLoader.loadClass("com.example.EnumWithExtendedCharacters");
}

From source file:com.mirantis.cachemod.filter.CacheConfiguration.java

private Object initClass(FilterConfig config, String classInitParam, Class interfaceClass) {
    String className = config.getInitParameter(classInitParam);
    if (className != null) {
        try {/*from  ww w.j  a  v  a2 s. c o  m*/
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                classLoader = this.getClass().getClassLoader();
            }
            Class clazz = classLoader.loadClass(className);
            if (!interfaceClass.isAssignableFrom(clazz)) {
                log.error("CacheFilter: Specified class '" + className + "' does not implement"
                        + interfaceClass.getName());
                return null;
            } else {
                return clazz.newInstance();
            }
        } catch (ClassNotFoundException e) {
            log.error("CacheFilter: Class '" + className + "' not found.", e);
        } catch (InstantiationException e) {
            log.error("CacheFilter: Class '" + className
                    + "' could not be instantiated because it is not a concrete class.", e);
        } catch (IllegalAccessException e) {
            log.error("CacheFilter: Class '" + className
                    + "' could not be instantiated because it is not public.", e);
        }
    }
    return null;
}

From source file:com.nxttxn.vramel.impl.converter.AnnotationTypeConverterLoader.java

/**
 * Filters the given list of packages and returns an array of <b>only</b> package names.
 * <p/>/*  www  .j a va 2  s . c  o m*/
 * This implementation will check the given list of packages, and if it contains a class name,
 * that class will be loaded directly and added to the list of classes. This optimizes the
 * type converter to avoid excessive file scanning for .class files.
 *
 * @param resolver the class resolver
 * @param packageNames the package names
 * @param classes to add loaded @Converter classes
 * @return the filtered package names
 */
protected String[] filterPackageNamesOnly(PackageScanClassResolver resolver, String[] packageNames,
        Set<Class<?>> classes) {
    if (packageNames == null || packageNames.length == 0) {
        return packageNames;
    }

    // optimize for CorePackageScanClassResolver
    if (resolver.getClassLoaders().isEmpty()) {
        return packageNames;
    }

    // the filtered packages to return
    List<String> packages = new ArrayList<String>();

    // try to load it as a class first
    for (String name : packageNames) {
        // must be a FQN class name by having an upper case letter
        if (StringHelper.hasUpperCase(name)) {
            Class<?> clazz = null;
            for (ClassLoader loader : resolver.getClassLoaders()) {
                try {
                    clazz = loader.loadClass(name);
                    LOG.trace("Loaded {} as class {}", name, clazz);
                    classes.add(clazz);
                    // class founder, so no need to load it with another class loader
                    break;
                } catch (Throwable e) {
                    // do nothing here
                }
            }
            if (clazz == null) {
                // ignore as its not a class (will be package scan afterwards)
                packages.add(name);
            }
        } else {
            // ignore as its not a class (will be package scan afterwards)
            packages.add(name);
        }
    }

    // return the packages which is not FQN classes
    return packages.toArray(new String[packages.size()]);
}

From source file:org.jsonschema2pojo.integration.EnumIT.java

@Test
public void multipleEnumArraysWithSameName() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/enum/multipleEnumArraysWithSameName.json", "com.example");

    resultsClassLoader.loadClass("com.example.MultipleEnumArraysWithSameName");
    resultsClassLoader.loadClass("com.example.Status");
    resultsClassLoader.loadClass("com.example.Status_");
}

From source file:net.java.dev.weblets.impl.WebletContainerImpl.java

public Weblet getWeblet(String webletName) {
    Weblet weblet = (Weblet) _weblets.get(webletName);
    if (weblet == null) {
        try {// www.jav  a 2s.c  o  m
            WebletConfigImpl config = (WebletConfigImpl) _webletConfigs.get(webletName);
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class webletClass = loader.loadClass(config.getWebletClass());
            weblet = (Weblet) webletClass.newInstance();
            weblet.init(config);
            _weblets.put(webletName, weblet);
        } catch (ClassNotFoundException e) {
            throw new WebletException(e);
        } catch (InstantiationException e) {
            throw new WebletException(e);
        } catch (IllegalAccessException e) {
            throw new WebletException(e);
        }
    }
    return weblet;
}

From source file:Main.java

/** Search the handlerPkgs for URLStreamHandler classes matching the
 * pkg + protocol + ".Handler" naming convention.
 *
 * @see #checkHandlerPkgs()/*www.ja va2  s . co  m*/
 * @param protocol The protocol to create a stream handler for
 * @return The protocol handler or null if not found
 */
public URLStreamHandler createURLStreamHandler(final String protocol) {
    // Check the handler map
    URLStreamHandler handler = (URLStreamHandler) handlerMap.get(protocol);
    if (handler != null)
        return handler;

    // Validate that createURLStreamHandler is not recursing
    String prevProtocol = (String) createURLStreamHandlerProtocol.get();
    if (prevProtocol != null && prevProtocol.equals(protocol))
        return null;
    createURLStreamHandlerProtocol.set(protocol);

    // See if the handler pkgs definition has changed
    checkHandlerPkgs();

    // Search the handlerPkgs for a matching protocol handler
    ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
    for (int p = 0; p < handlerPkgs.length; p++) {
        try {
            // Form the standard protocol handler class name
            String classname = handlerPkgs[p] + "." + protocol + ".Handler";
            Class type = null;

            try {
                type = ctxLoader.loadClass(classname);
            } catch (ClassNotFoundException e) {
                // Try our class loader
                type = Class.forName(classname);
            }

            if (type != null) {
                handler = (URLStreamHandler) type.newInstance();
                handlerMap.put(protocol, handler);
            }
        } catch (Throwable ignore) {
        }
    }

    createURLStreamHandlerProtocol.set(null);
    return handler;
}

From source file:com.quinsoft.zeidon.standardoe.JavaObjectEngine.java

/**
 * Starts the browser.  This method is public so that it can be called directly from Eclipse.
 *//*from   w w w .  java2s. c  o m*/
@Override
@SuppressWarnings("unchecked") // for classLoader.
public boolean startBrowser() {
    String browserClassName = "com.quinsoft.zeidon.objectbrowser.Starter";
    try {
        // Load browser class dynamically so we don't have to have the browser to compile.
        ClassLoader classLoader = getClassLoader(browserClassName);
        Class<BrowserStarter> starterClass;
        starterClass = (Class<BrowserStarter>) classLoader.loadClass(browserClassName);
        BrowserStarter starter = starterClass.newInstance();
        starter.startBrowser(this);
        return true;
    } catch (Exception e) {
        systemTask.log().error("Couldn't find browser class %s", e, browserClassName);
        return false;
    }
}

From source file:org.jacpfx.vertx.spring.SpringVerticleFactory.java

@Override
public synchronized Verticle createVerticle(final String verticleName, final ClassLoader classLoader)
        throws Exception {
    final String className = VerticleFactory.removePrefix(verticleName);
    Class<?> clazz;//  w  ww . ja  v a  2s  .c  o  m
    if (className.endsWith(SUFFIX)) {
        CompilingClassLoader compilingLoader = new CompilingClassLoader(classLoader, className);
        clazz = compilingLoader.loadClass(compilingLoader.resolveMainClassName());
    } else {
        clazz = classLoader.loadClass(className);
    }
    return createVerticle(clazz, classLoader);
}

From source file:org.jsonschema2pojo.integration.AdditionalPropertiesIT.java

@Test(expected = UnrecognizedPropertyException.class)
public void additionalPropertiesAreNotDeserializableWhenDisallowed()
        throws ClassNotFoundException, SecurityException, NoSuchMethodException, IOException {

    ClassLoader resultsClassLoader = schemaRule
            .generateAndCompile("/schema/additionalProperties/noAdditionalProperties.json", "com.example");

    Class<?> classWithNoAdditionalProperties = resultsClassLoader
            .loadClass("com.example.NoAdditionalProperties");

    mapper.readValue("{\"a\":\"1\", \"b\":2}", classWithNoAdditionalProperties);

}

From source file:au.org.ala.delta.util.Utils.java

private static void launchIntkeyViaClassLoader(String inputFile) throws Exception {
    // Gah.... this is a horrible work around for the fact that
    // the swing application framework relies on a static
    // Application instance so we can't have the Editor and
    // Intkey playing together nicely in the same JVM.
    // It doesn't really work properly anyway, the swing application
    // framework generates exceptions during loading and saving
    // state due to failing instanceof checks.
    String classPath = System.getProperty("java.class.path");
    String[] path = classPath.split(File.pathSeparator);
    List<URL> urls = new ArrayList<URL>();
    for (String pathEntry : path) {
        urls.add(new File(pathEntry).toURI().toURL());
    }//from   ww w .ja va2  s . c om
    ClassLoader intkeyLoader = new URLClassLoader(urls.toArray(new URL[0]),
            ClassLoader.getSystemClassLoader().getParent());
    Class<?> intkey = intkeyLoader.loadClass("au.org.ala.delta.intkey.Intkey");
    Method main = intkey.getMethod("main", String[].class);
    main.invoke(null, (Object) new String[] { inputFile });
}