Example usage for java.lang ClassLoader getSystemClassLoader

List of usage examples for java.lang ClassLoader getSystemClassLoader

Introduction

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

Prototype

@CallerSensitive
public static ClassLoader getSystemClassLoader() 

Source Link

Document

Returns the system class loader.

Usage

From source file:Main.java

/**
 * Load a given resource. <p/> This method will try to load the resource
 * using the following methods (in order):
 * <ul>//  w ww  .jav  a 2 s.  c  o m
 * <li>From Thread.currentThread().getContextClassLoader()
 * <li>From ClassLoaderUtil.class.getClassLoader()
 * <li>callingClass.getClassLoader()
 * </ul>
 * 
 * @param resourceName The name of the resource to load
 * @param callingClass The Class object of the calling object
 */
public static URL getResource(String resourceName, Class callingClass) {
    URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = Thread.currentThread().getContextClassLoader().getResource(resourceName.substring(1));
    }

    ClassLoader cluClassloader = Main.class.getClassLoader();
    if (cluClassloader == null) {
        cluClassloader = ClassLoader.getSystemClassLoader();
    }
    if (url == null) {
        url = cluClassloader.getResource(resourceName);
    }
    if (url == null && resourceName.startsWith("/")) {
        //certain classloaders need it without the leading /
        url = cluClassloader.getResource(resourceName.substring(1));
    }

    if (url == null) {
        ClassLoader cl = callingClass.getClassLoader();

        if (cl != null) {
            url = cl.getResource(resourceName);
        }
    }

    if (url == null) {
        url = callingClass.getResource(resourceName);
    }

    if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) {
        return getResource('/' + resourceName, callingClass);
    }

    return url;
}

From source file:Main.java

/**
 * Tries to load the class from the preferred loader.  If not successful, tries to 
 * load the class from the current thread's context class loader or system class loader.
 * @param classname Desired class name./*w w  w .j  a v a 2  s.c om*/
 * @param preferredLoader The preferred class loader
 * @return the loaded class.
 * @throws ClassNotFoundException if the class could not be loaded by any loader
 */
public static Class<?> loadClass(String classname, ClassLoader preferredLoader) throws ClassNotFoundException {
    ClassNotFoundException exception = null;
    for (ClassLoader loader : Arrays.asList(preferredLoader, Thread.currentThread().getContextClassLoader(),
            ClassLoader.getSystemClassLoader())) {
        try {
            return loader.loadClass(classname);
        } catch (ClassNotFoundException e) {
            if (exception == null) {
                exception = e;
            }
        }
    }
    throw exception;
}

From source file:com.hexidec.util.Translatrix.java

public static void init(String bundle, Locale locale) {

    if (langResources != null) {
        return;/*from w w  w .  j a  va2  s. c  o  m*/
    }

    try {
        langResources = ResourceBundle.getBundle(bundle, locale, ClassLoader.getSystemClassLoader());
    } catch (MissingResourceException mre) {
        logException("MissingResourceException while loading language file", mre);
    }
}

From source file:ContextClassLoader.java

/**
 * Loads a class starting from the given class loader (can be null, then use default class loader)
 *
 * @param loader/*from   ww w  .java  2 s . c  o m*/
 * @param name   of class to load
 * @return
 * @throws ClassNotFoundException
 */
public static Class forName(final ClassLoader loader, final String name) throws ClassNotFoundException {
    Class klass = null;
    if (loader != null) {
        klass = Class.forName(name, false, loader);
    } else {
        klass = Class.forName(name, false, ClassLoader.getSystemClassLoader());
    }
    return klass;
}

From source file:org.o3project.odenos.core.util.ComponentLoader.java

/**
 * create Class Loader./*from   www. j a  v a 2  s.c om*/
 * @param dirname package path name.
 * @return class loader.
 * @throws IOException exception.
 */
public static ClassLoader createClassLoader(final String dirname) throws IOException {
    URL[] url = new URL[1];
    File file;
    if (dirname.endsWith("/")) {
        file = new File(dirname);
    } else {
        file = new File(dirname + "/");
    }
    url[0] = file.toURI().toURL();

    ClassLoader parent = ClassLoader.getSystemClassLoader();
    URLClassLoader loader = new URLClassLoader(url, parent);

    return loader;
}

From source file:com.bits.protocolanalyzer.mvc.controller.HomeController.java

@RequestMapping
public ModelAndView home() {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    ModelAndView mav = new ModelAndView("home");
    mav.addObject("paths", urls);
    return mav;/*  w  w w .j av  a  2s  .  c om*/
}

From source file:org.springframework.cloud.dataflow.app.utils.ClassloaderUtils.java

/**
 * Creates a ClassLoader for the launched modules by merging the URLs supplied as argument with the URLs that
 * make up the additional classpath of the launched JVM (retrieved from the application classloader), and
 * setting the extension classloader of the JVM as parent, if accessible.
 *
 * @param urls a list of library URLs//ww  w .  ja v  a2 s  .  co m
 * @return the resulting classloader
 */
public static ClassLoader createModuleClassloader(URL[] urls) {
    ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
    if (log.isDebugEnabled()) {
        log.debug("systemClassLoader is " + systemClassLoader);
    }
    if (systemClassLoader instanceof URLClassLoader) {
        // add the URLs of the application classloader to the created classloader
        // to compensate for LaunchedURLClassLoader not delegating to parent to retrieve resources
        @SuppressWarnings("resource")
        URLClassLoader systemUrlClassLoader = (URLClassLoader) systemClassLoader;
        URL[] mergedUrls = new URL[urls.length + systemUrlClassLoader.getURLs().length];
        if (log.isDebugEnabled()) {
            log.debug("Original URLs: " + StringUtils.arrayToCommaDelimitedString(urls));
            log.debug("Java Classpath URLs: "
                    + StringUtils.arrayToCommaDelimitedString(systemUrlClassLoader.getURLs()));
        }
        System.arraycopy(urls, 0, mergedUrls, 0, urls.length);
        System.arraycopy(systemUrlClassLoader.getURLs(), 0, mergedUrls, urls.length,
                systemUrlClassLoader.getURLs().length);
        // add the extension classloader as parent to the created context, if accessible
        if (log.isDebugEnabled()) {
            log.debug("Classloader URLs: " + StringUtils.arrayToCommaDelimitedString(mergedUrls));
        }
        return new LaunchedURLClassLoader(mergedUrls, systemUrlClassLoader.getParent());
    }
    return new LaunchedURLClassLoader(urls, systemClassLoader);
}

From source file:Main.java

private static String getSystemProperty(String key, String def) {
    try {//from  ww w .  ja v  a 2  s  . c om
        final ClassLoader cl = ClassLoader.getSystemClassLoader();
        final Class<?> SystemProperties = cl.loadClass("android.os.SystemProperties");
        final Class<?>[] paramTypes = new Class[] { String.class, String.class };
        final Method get = SystemProperties.getMethod("get", paramTypes);
        final Object[] params = new Object[] { key, def };
        return (String) get.invoke(SystemProperties, params);
    } catch (Exception e) {
        return def;
    }
}

From source file:org.tros.utils.logging.Logging.java

private static void copyFile(BuildInfo binfo, Class init, File logProp) {
    try {//  w w w.j a  v  a 2 s  .  c  o m
        String prop_file = init.getCanonicalName().replace('.', '/') + ".properties";
        java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader().getResources(prop_file);
        if (resources.hasMoreElements()) {
            URL to_use = resources.nextElement();
            try (FileOutputStream fis = new FileOutputStream(logProp)) {
                IOUtils.copy(to_use.openStream(), fis);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.eincs.decanter.render.soy.SoyAcre.java

/**
 * //from w ww.  j ava2s. c o  m
 * @return
 */
public static SoyAcre forClasspath() {
    final Reflections reflections = new Reflections(new ConfigurationBuilder()
            .addUrls(ClasspathHelper.forJavaClassPath()).setScanners(new ResourcesScanner()));
    final Set<String> soyFiles = reflections.getResources(Pattern.compile(SOY_FILE_NAME_PATTERN));
    final ClassLoader clazzLoader = ClassLoader.getSystemClassLoader();

    return new SoyAcre() {
        @Override
        public void addToFileSet(SoyFileSet.Builder fileSetBuilder) {
            for (String soyFile : soyFiles) {
                fileSetBuilder.add(clazzLoader.getResource(soyFile));
            }
        }
    };
}