Example usage for java.lang ClassLoader getClass

List of usage examples for java.lang ClassLoader getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.glowroot.agent.impl.BytecodeServiceImpl.java

@Override
public void preloadSomeSuperTypes(ClassLoader loader, @Nullable String className) {
    if (className == null) {
        return;/*from w  w  w  . j  ava  2s  .com*/
    }
    Set<String> preloadSomeSuperTypes = preloadSomeSuperTypesCache.get(className);
    if (preloadSomeSuperTypes.isEmpty()) {
        return;
    }
    Set<String> currentlyLoadingTypes = currentlyLoadingTypesHolder.get();
    boolean topLevel;
    if (currentlyLoadingTypes == null) {
        // using linked hash set so that top level class can be found as first element
        currentlyLoadingTypes = Sets.newLinkedHashSet();
        currentlyLoadingTypesHolder.set(currentlyLoadingTypes);
        topLevel = true;
    } else if (currentlyLoadingTypes.iterator().next().equals(className)) {
        // not top level, and need to abort the (nested) defineClass() that this is inside of,
        // otherwise the defineClass() that this is inside of will succeed, but then the top
        // level defineClass() will fail with "attempted duplicate class definition for name"
        throw new AbortPreload();
    } else {
        topLevel = false;
    }
    if (!currentlyLoadingTypes.add(className)) {
        // already loading className, prevent infinite loop / StackOverflowError, see
        // AnalyzedClassPlanBeeWithBadPreloadCacheIT
        return;
    }
    try {
        for (String superClassName : preloadSomeSuperTypes) {
            logger.debug("pre-loading super class {} for {}, in loader={}@{}", superClassName, className,
                    loader.getClass().getName(), loader.hashCode());
            try {
                Class.forName(superClassName, false, loader);
            } catch (ClassNotFoundException e) {
                logger.debug("super class {} not found (for sub-class {})", superClassName, className, e);
            } catch (LinkageError e) {
                // this can happen, e.g. ClassCircularityError, under strange circumstances,
                // see AnalyzedClassPlanBeeWithMoreBadPreloadCacheIT
                logger.debug("linkage error occurred while loading super class {} (for" + " sub-class {})",
                        superClassName, className, e);
            } catch (AbortPreload e) {
            }
        }
    } finally {
        if (topLevel) {
            currentlyLoadingTypesHolder.remove();
        } else {
            currentlyLoadingTypes.remove(className);
        }
    }
}

From source file:org.graphwalker.Util.java

public static File getFile(final String resourceName) {
    Util.logger.debug("Try to get file: " + resourceName);
    File file = new File(resourceName);
    if (file.exists()) {
        Util.logger.debug("File exists on file system.");
        return file;
    }/*w w w  .ja va2s.  c  om*/
    ClassLoader cloader = Thread.currentThread().getContextClassLoader();
    Util.logger.debug("Class loader class name: " + cloader.getClass().getName());
    URL resource = cloader.getResource(resourceName);

    if (resource == null) {
        throw new IllegalArgumentException("Could not get resource: " + resourceName);
    }

    return new File(resource.getPath());
}

From source file:org.kuali.coeus.sys.impl.KcConfigVerifier.java

/**
 * Checks if the Spring Instrumenting ClassLoader is in the ClassLoader chain. If so, this means
 * that it is properly configured./*from   w ww .j a va 2 s  .  c o m*/
 */
protected boolean tomcatInstrumentingClassLoaderConfigured() {
    //generally this means that the tomcat context.xml file has tomcat ClassLoader configured.  If not then
    //something really strange is going on
    ClassLoader cl = this.getClass().getClassLoader();
    while (cl != null) {
        if (TOMCAT_INSTRUMENTATION_CLASS_LOADER_CLASS_NAME.equals(cl.getClass().getName())) {
            return true;
        }
        cl = cl.getParent();
    }
    return false;
}

From source file:org.meveo.commons.utils.ReflectionUtils.java

@SuppressWarnings("rawtypes")
public static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException {

    try {//  w  ww.  j  a v a  2  s .c  o m
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        Class CL_class = classLoader.getClass();
        while (CL_class != java.lang.ClassLoader.class) {
            CL_class = CL_class.getSuperclass();
        }
        java.lang.reflect.Field ClassLoader_classes_field = CL_class.getDeclaredField("classes");
        ClassLoader_classes_field.setAccessible(true);
        Vector classes = (Vector) ClassLoader_classes_field.get(classLoader);

        ArrayList<Class> classList = new ArrayList<Class>();

        for (Object clazz : classes) {
            if (((Class) clazz).getName().startsWith(packageName)) {
                classList.add((Class) clazz);
            }
        }

        return classList;

    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        logger.error("Failed to get a list of classes", e);
    }

    return new ArrayList<Class>();
}

From source file:org.milyn.classpath.Scanner.java

public void scanClasspath(ClassLoader classLoader) throws IOException {

    if (!(classLoader instanceof URLClassLoader)) {
        logger.warn("Not scanning classpath for ClassLoader '" + classLoader.getClass().getName()
                + "'.  ClassLoader must implement '" + URLClassLoader.class.getName() + "'.");
        return;/*from  www  .ja  v a2 s .c  o  m*/
    }

    URL[] urls = ((URLClassLoader) classLoader).getURLs();
    Set alreadyScanned = new HashSet();

    for (URL url : urls) {
        String urlPath = url.getFile();

        urlPath = URLDecoder.decode(urlPath, "UTF-8");
        if (urlPath.startsWith("file:")) {
            urlPath = urlPath.substring(5);
        }

        if (urlPath.indexOf('!') > 0) {
            urlPath = urlPath.substring(0, urlPath.indexOf('!'));
        }

        File file = new File(urlPath);
        if (alreadyScanned.contains(file.getAbsolutePath())) {
            logger.debug("Ignoring classpath URL '" + file.getAbsolutePath() + "'.  Already scanned this URL.");
            continue;
        }
        if (file.isDirectory()) {
            handleDirectory(file, null);
        } else {
            handleArchive(file);
        }
        alreadyScanned.add(file.getAbsolutePath());
    }
}

From source file:org.mule.module.launcher.application.CompositeApplicationClassLoader.java

private Method findDeclaredMethod(ClassLoader classLoader, String methodName, Class<?>... params)
        throws NoSuchMethodException {
    Class clazz = classLoader.getClass();

    while (clazz != null) {
        try {//from  w  w w  .  java  2s  .  c  o m
            Method findLibraryMethod = clazz.getDeclaredMethod(methodName, params);
            findLibraryMethod.setAccessible(true);

            return findLibraryMethod;
        } catch (NoSuchMethodException e) {
            clazz = clazz.getSuperclass();
        }
    }

    throw new NoSuchMethodException(
            String.format("Cannot find a method '%s' with the given parameter types '%s'", methodName,
                    Arrays.toString(params)));
}

From source file:org.mule.tck.junit4.ExtensionsFunctionalTestCase.java

private void generateResourcesAndAddToClasspath(ResourcesGenerator generator) throws Exception {
    ClassLoader cl = getClass().getClassLoader();
    Method method = findMethod(cl.getClass(), "addURL", URL.class);
    method.setAccessible(true);/*  w  ww  . j  a  v  a  2s .c  om*/

    for (GeneratedResource resource : generator.dumpAll()) {
        URL generatedResourceURL = new File(generatedResourcesDirectory, resource.getFilePath()).toURI()
                .toURL();
        method.invoke(cl, generatedResourceURL);
    }
}

From source file:org.mule.util.ClassUtils.java

public static void addLibrariesToClasspath(List urls)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    ClassLoader sys = ClassLoader.getSystemClassLoader();
    if (!(sys instanceof URLClassLoader)) {
        throw new IllegalArgumentException(
                "PANIC: Mule has been started with an unsupported classloader: " + sys.getClass().getName()
                        + ". " + "Please report this error to user<at>mule<dot>codehaus<dot>org");
    }// w w w .j  a  v a2  s.  co  m

    // system classloader is in this case the one that launched the application,
    // which is usually something like a JDK-vendor proprietary AppClassLoader
    URLClassLoader sysCl = (URLClassLoader) sys;

    /*
    * IMPORTANT NOTE: The more 'natural' way would be to create a custom
    * URLClassLoader and configure it, but then there's a chicken-and-egg
    * problem, as all classes MuleBootstrap depends on would have been loaded by
    * a parent classloader, and not ours. There's no straightforward way to
    * change this, and is documented in a Sun's classloader guide. The solution
    * would've involved overriding the ClassLoader.findClass() method and
    * modifying the semantics to be child-first, but that way we are calling for
    * trouble. Hacking the primordial classloader is a bit brutal, but works
    * perfectly in case of running from the command-line as a standalone app.
    * All Mule embedding options then delegate the classpath config to the
    * embedder (a developer embedding Mule in the app), thus classloaders are
    * not modified in those scenarios.
    */

    // get a Method ref from the normal class, but invoke on a proprietary parent
    // object,
    // as this method is usually protected in those classloaders
    Class refClass = URLClassLoader.class;
    Method methodAddUrl = refClass.getDeclaredMethod("addURL", new Class[] { URL.class });
    methodAddUrl.setAccessible(true);
    for (Iterator it = urls.iterator(); it.hasNext();) {
        URL url = (URL) it.next();
        methodAddUrl.invoke(sysCl, url);
    }
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java

/**
 * Adds the shared lib to the thread context class loader (they need to be added to where the
 * openspaces.jar class exists).//from   w  ww .  j av  a2  s .co  m
 */
private void addUrlsToContextClassLoader(URL[] urls) {
    if (addedSharedLibToClassLoader) {
        return;
    }
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Class clazz = classLoader.getClass();
    while (clazz != Object.class && !URLClassLoader.class.equals(clazz)) {
        clazz = clazz.getSuperclass();
    }
    if (clazz == Object.class) {
        throw new CannotCreateContainerException(
                "Failed to find URLClassLoader to add shared lib for " + classLoader.getClass());
    }

    try {
        Method addURL = clazz.getDeclaredMethod("addURL", URL.class);
        addURL.setAccessible(true);
        for (URL url : urls) {
            addURL.invoke(classLoader, url);
        }
    } catch (Exception e) {
        throw new CannotCreateContainerException(
                "Failed to add shared lib to thread context class loader [" + classLoader + "]", e);
    }
    addedSharedLibToClassLoader = true;
}

From source file:org.pentaho.platform.plugin.services.pluginmgr.PluginResourceLoader.java

protected ClassLoader getClassLoader(Class<?> clazz) {
    PluginClassLoader _overrideClassloader = getOverrideClassloader();
    ClassLoader classLoader = (_overrideClassloader != null) ? _overrideClassloader : clazz.getClassLoader();

    if (!PluginClassLoader.class.isAssignableFrom(classLoader.getClass())) {
        Logger.warn(this,
                Messages.getInstance().getString("PluginResourceLoader.WARN_CLASS_LOADED_OUTSIDE_OF_PLUGIN_ENV",
                        clazz.getName(), PluginClassLoader.class.getSimpleName(),
                        this.getClass().getSimpleName())); //$NON-NLS-1$
    }/*from   w  w  w. j  av a 2s  . c  o m*/
    return classLoader;
}