Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

In this page you can find the example usage for java.lang Class getClassLoader.

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTask.java

private static FTPTaskMirror createMirror(FTPTask task, ClassLoader loader) {
    try {//from   www .j a v  a 2  s  .  c om
        loader.loadClass("org.apache.commons.net.ftp.FTP"); // sanity check
    } catch (ClassNotFoundException e) {
        throw new BuildException("The <classpath> for <ftp> must include"
                + " commons-net.jar if not in Ant's own " + " classpath", e, task.getLocation());
    }
    try {
        Class c = loader.loadClass(FTPTaskMirror.class.getName() + "Impl");
        if (c.getClassLoader() != loader) {
            throw new BuildException("Overdelegating loader", task.getLocation());
        }
        Constructor cons = c.getConstructor(new Class[] { FTPTask.class });
        return (FTPTaskMirror) cons.newInstance(new Object[] { task });
    } catch (Exception e) {
        throw new BuildException(e, task.getLocation());
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil.java

/**
 * Find a jar that contains a class of the same name, if any. It will return
 * a jar file, even if that is not the first thing on the class path that
 * has a class with the same name. Looks first on the classpath and then in
 * the <code>packagedClasses</code> map.
 * @param my_class the class to find./*from www  .  jav a  2  s  .c  om*/
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses)
        throws IOException {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";

    // first search the classpath
    for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
        URL url = itr.nextElement();
        if ("jar".equals(url.getProtocol())) {
            String toReturn = url.getPath();
            if (toReturn.startsWith("file:")) {
                toReturn = toReturn.substring("file:".length());
            }
            // URLDecoder is a misnamed class, since it actually decodes
            // x-www-form-urlencoded MIME type rather than actual
            // URL encoding (which the file path has). Therefore it would
            // decode +s to ' 's which is incorrect (spaces are actually
            // either unencoded or encoded as "%20"). Replace +s first, so
            // that they are kept sacred during the decoding process.
            toReturn = toReturn.replaceAll("\\+", "%2B");
            toReturn = URLDecoder.decode(toReturn, "UTF-8");
            return toReturn.replaceAll("!.*$", "");
        }
    }

    // now look in any jars we've packaged using JarFinder. Returns null when
    // no jar is found.
    return packagedClasses.get(class_file);
}

From source file:gov.nih.nci.caarray.external.v1_0.AbstractCaArrayEntityTest.java

public static <T> List<Class<? extends T>> findLocalSubclasses(Class<T> c)
        throws ClassNotFoundException, URISyntaxException {
    List<Class<? extends T>> l = new ArrayList<Class<? extends T>>();
    File dir = new File(c.getProtectionDomain().getCodeSource().getLocation().toURI());
    Iterator<File> fi = FileUtils.iterateFiles(dir, new String[] { "class" }, true);
    int prefix = dir.getAbsolutePath().length() + 1;
    int suffix = ".class".length();
    while (fi.hasNext()) {
        File cf = fi.next();//from ww  w.  j  a  va2s. co m
        String fn = cf.getAbsolutePath();
        try {
            String cn = fn.substring(prefix, fn.length() - suffix);
            if (cn.endsWith("<error>")) {
                continue;
            }
            cn = cn.replace('/', '.');
            System.out.println("cn = " + cn);
            Class tmp = c.getClassLoader().loadClass(cn);
            if ((tmp.getModifiers() & Modifier.ABSTRACT) != 0) {
                continue;
            }
            if (c.isAssignableFrom(tmp)) {
                l.add(tmp);
                System.out.println("added " + cf.getAbsolutePath() + " as " + cn);
            }
        } catch (Exception e) {
            System.err.println(fn);
            e.printStackTrace();
        }
    }
    return l;
}

From source file:net.sf.jasperreports.engine.util.JRResourcesUtil.java

/**
 * Attempts to find a resource using a class loader.
 * <p/>/*from   w  ww  .ja v a 2 s .co  m*/
 * The following sources are tried:
 * <ul>
 *    <li>the class loader returned by {@link #getClassLoader(ClassLoader) getClassLoader(ClassLoader)}</li>
 *    <li>the context class loader</li>
 *    <li><code>clazz.getClassLoader()</code></li>
 *    <li><code>clazz.getResource()</code></li>
 * </ul>
 * 
 * @param location the resource name
 * @param clsLoader a class loader
 * @param clazz a class
 * @return the resource URL if found
 * @deprecated Replaced by {@link #findClassLoaderResource(String, ClassLoader)}.
 */
public static URL findClassLoaderResource(String location, ClassLoader clsLoader, Class<?> clazz) {
    ClassLoader classLoader = getClassLoader(clsLoader);

    URL url = null;

    if (classLoader != null) {
        url = classLoader.getResource(location);
    }

    if (url == null) {
        classLoader = Thread.currentThread().getContextClassLoader();

        if (classLoader != null) {
            url = classLoader.getResource(location);
        }

        if (url == null) {
            classLoader = clazz.getClassLoader();
            if (classLoader == null) {
                url = clazz.getResource("/" + location);
            } else {
                url = classLoader.getResource(location);
            }
        }
    }

    return url;
}

From source file:net.ymate.platform.core.util.ClassUtils.java

public static Class<?> loadClass(String className, Class<?> callingClass) throws ClassNotFoundException {
    Class<?> _targetClass = null;
    try {/*ww w  . j a  va  2 s  .  c om*/
        _targetClass = Thread.currentThread().getContextClassLoader().loadClass(className);
    } catch (ClassNotFoundException e) {
        try {
            _targetClass = Class.forName(className, false, ClassUtils.class.getClassLoader());
        } catch (ClassNotFoundException ex) {
            try {
                _targetClass = _INNER_CLASS_LOADER.loadClass(className);
            } catch (ClassNotFoundException exc) {
                _targetClass = callingClass.getClassLoader().loadClass(className);
            }
        }
    }
    return _targetClass;
}

From source file:org.apache.taverna.prov.W3ProvenanceExport.java

/** Extract our own plugin version - if running within Raven */
protected static URI getPluginIdentifier(Class<?> pluginClass) {
    ClassLoader classLoader = pluginClass.getClassLoader();
    String className = pluginClass.getCanonicalName();

    try {//  ww w.j  a  va 2  s .c  o  m
        //            org.osgi.framework.Bundle osgiBundle = FrameworkUtil
        //                    .getBundle(pluginClass);
        //            if (osgiBundle != null) {
        //                String symbolicName = osgiBundle.getSymbolicName();
        //                Version version = osgiBundle.getVersion();
        //            }

        // equivalent as above without OSGi dependency:
        Object bundle = PropertyUtils.getProperty(classLoader, "bundle");
        String symbolicName = BeanUtils.getProperty(bundle, "symbolicName");
        String version = BeanUtils.getProperty(bundle, "version").toString();

        // NOTE: The above code has not been tested within OSGi as of 2013-12-18

        return osgiURI.resolve(uriTools.validFilename(symbolicName) + "/" + uriTools.validFilename(version));
    } catch (IllegalAccessException | InvocationTargetException | NullPointerException
            | NoSuchMethodException e) {
        // Assume it's not OSGi
    }

    // Not OSGi, try as Raven:
    try {

        //            Artifact artifact = ((LocalArtifactClassLoader) classLoader)
        //                    .getArtifact();
        //            String groupId = artifact.getGroupId();
        //            String artifactId = artifact.getArtifactId();
        //            String version = artifact.getVersion();

        // Equivalent as above, but without Raven dependency:

        Object artifact = PropertyUtils.getProperty(classLoader, "artifact");
        if (artifact == null) {
            return null;
        }
        // If it worked, then we assume it is a
        // net.sf.taverna.raven.repository.Artifact
        // implementation
        String groupId = BeanUtils.getProperty(artifact, "groupId");
        String artifactId = BeanUtils.getProperty(artifact, "artifactId");
        String version = BeanUtils.getProperty(artifact, "version");
        //  mimic scufl2-t2flow
        return ravenURI.resolve(uriTools.validFilename(groupId) + "/" + uriTools.validFilename(artifactId) + "/"
                + uriTools.validFilename(version) + "/" + uriTools.validFilename(className));
    } catch (IllegalAccessException | InvocationTargetException | NullPointerException
            | NoSuchMethodException e) {
        // Assume it's not Raven
    }

    // Fallback based on the classname - mimic scufl2-t2flow
    return ravenURI.resolve("undefined/" + uriTools.validFilename(className));

}

From source file:com.sworddance.util.WeakProxy.java

@SuppressWarnings("unchecked")
public static <T> T newProxyInstance(final Object referent, Callable<T> restoreCallable,
        Class<?>... interfaces) {
    if (referent == null && restoreCallable == null) {
        return null;
    } else {/*w ww  .j  av  a  2s  .co m*/
        Class<?> clazz = getFirst(interfaces);
        T actualReferent = (T) getActual(referent);
        if (clazz == null) {
            if (actualReferent == null) {
                actualReferent = invokeCallable(restoreCallable);
            }
            ApplicationIllegalArgumentException.notNull(actualReferent,
                    "referent must be not null if there are no listed classes");
            clazz = actualReferent.getClass();
            interfaces = clazz.getInterfaces();
        }
        Reference<T> objectRef = newWeakReference(actualReferent);
        ProxyInvocationHandler<T> invocationHandler = new ProxyInvocationHandler<T>(objectRef, restoreCallable,
                interfaces);
        T t = invocationHandler.newProxyInstance(clazz.getClassLoader());
        return t;
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.SpringSecurityUtils.java

private static Object createDelegate(final String configKey, Class<?> interfaceClass, Class<?> implClass) {

    try {/* w w  w . jav  a  2  s .  c om*/
        storeInContext(configKey, implClass.newInstance());
    } catch (InstantiationException impossible) {
        // impossible with regular java.util classes
    } catch (IllegalAccessException impossible) {
        // impossible with regular java.util classes
    }

    return Proxy.newProxyInstance(implClass.getClassLoader(), new Class[] { interfaceClass },
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return method.invoke(getFromContext(configKey), args);
                }
            });
}

From source file:edu.indiana.lib.osid.base.loader.OsidLoader.java

/**
 * Get an InputStream for a particular file name - first check the sakai.home area and then
 * revert to the classpath.//from   ww w  . j  av  a  2s.c om
*
* This is a utility method used several places.
 */
public static java.io.InputStream getConfigStream(String fileName, Class curClass) {
    String sakaiHome = System.getProperty("sakai.home");
    String filePath = sakaiHome + fileName;

    try {
        java.io.File f = new java.io.File(filePath);
        if (f.exists()) {
            return new java.io.FileInputStream(f);
        }
    } catch (Throwable t) {
        // Not found in the sakai.home area
    }

    if (curClass == null)
        return null;

    // If there is a class context, load from the class context...
    java.io.InputStream istream = null;

    // Load from the class loader
    istream = curClass.getClassLoader().getResourceAsStream(fileName);
    if (istream != null)
        return istream;

    // Load from the class relative
    istream = curClass.getResourceAsStream(fileName);
    if (istream != null)
        return istream;

    // Loading from the class at the root
    istream = curClass.getResourceAsStream("/" + fileName);
    return istream;
}

From source file:illab.nabal.util.Util.java

/**
 * Get how many APIs given network delegate has.
 * /*www.  j  a v a2s  .  c  o  m*/
 * @param networkDelegate
 * @return how many APIs given network delegate has 
 */
public static int getHowManyApis(Delegate networkDelegate) {

    // method names to be exculded when counting 
    String[] excludedMethodNames = {
            // inherited from JDK
            "equals", "getClass", "hashCode", "notify", "notifyAll", "toString", "wait"
            // inherited from Delegate
            , "isSessionValid", "fetchSession", "purgeSession", "hasNoJobs", "getBitmapFromUrl" };

    // determine which socail network this delegate class represents
    Delegate delegate = networkDelegate;
    Class<? extends Delegate> thisClass = null;
    if (networkDelegate instanceof FacebookDelegate) {
        thisClass = ((FacebookDelegate) delegate).getClass();
    } else if (networkDelegate instanceof TwitterDelegate) {
        thisClass = ((TwitterDelegate) delegate).getClass();
    } else if (networkDelegate instanceof WeiboDelegate) {
        thisClass = ((WeiboDelegate) delegate).getClass();
    }

    // get max of method index
    int maxMethodIndex = 0;
    String thisClassName = thisClass.getName();
    ClassLoader classLoader = thisClass.getClassLoader();
    try {
        for (Method method : classLoader.loadClass(thisClassName).getMethods()) {
            if (Arrays.asList(excludedMethodNames).contains(method.getName()) == false) {
                //Log.v(TAG, "indexing... " + method.getName() + " : added");
                maxMethodIndex++;
            } else {
                //Log.v(TAG, "indexing... " + method.getName() + " : pass");
            }
        }
    } catch (ClassNotFoundException e) {
        // if error occurrs let's set 100 to prevent the shortage of the index
        maxMethodIndex = 100;
    }
    return maxMethodIndex;
}