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:Main.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * //from   w w  w . j a va  2 s.c om
 * @param clazz
 *          the Class
 * @param results -
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the clazz
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n");
    results.append(clazz.getName());
    results.append("(");
    results.append(Integer.toHexString(clazz.hashCode()));
    results.append(").ClassLoader=");
    results.append(cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n..");
        results.append(parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n....");
            results.append(urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) {
        results.append("\n++++CodeSource: ");
        results.append(clazzCS);
    } else
        results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        Class iface = ifaces[i];
        results.append("\n++");
        results.append(iface);
        results.append("(");
        results.append(Integer.toHexString(iface.hashCode()));
        results.append(")");
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: ");
        results.append(loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null) {
            results.append("\n++++CodeSource: ");
            results.append(cs);
        } else
            results.append("\n++++Null CodeSource");
    }
}

From source file:org.apache.beehive.controls.api.bean.Controls.java

/**
 * Helper method for initializing instances of declarative control clients (objects that use controls via @Control
 * and @EventHandler annotations).  This method runs the client-specific generated ClientInitializer class to do
 * its initialization work.// ww w  .j  a v a 2  s .c om
 *
 * @param cl the classloader used to load the ClientInitializer.  If null, defaults to the classloader used to
 *           load the client object being initialized.
 * @param client the client object being initialized.
 * @param cbc the ControlBeanContext to be associated with the client object (that will nest the controls the client
 *            defines).  If null, the thread-local context (possibly none) will be used.
 * @throws ControlException
 * @throws ClassNotFoundException
 */
public static void initializeClient(ClassLoader cl, Object client, ControlBeanContext cbc)
        throws ClassNotFoundException {
    Class clientClass = client.getClass();
    String clientName = clientClass.getName();

    if (cl == null)
        cl = clientClass.getClassLoader();

    String initName = clientName + "ClientInitializer";
    Class initClass = cl.loadClass(initName);

    try {
        Method m = initClass.getMethod("initialize", ControlBeanContext.class, clientClass);
        m.invoke(null, cbc, client);
    } catch (Throwable e) {
        if (e instanceof InvocationTargetException) {
            if (e.getCause() != null) {
                e = e.getCause();
            }
        }

        throw new ControlException(
                "Exception trying to run client initializer: " + e.getClass().getName() + ", " + e.getMessage(),
                e);
    }
}

From source file:org.carrot2.util.attribute.BindableDescriptorUtils.java

/**
 * @return Returns the descriptor class for a class marked with {@link Bindable}.
 * @throws IllegalArgumentException If the class is not annotated with {@link Bindable}.
 * @throws NoClassDefFoundError If the descriptor cannot be found.
 *//* w  ww  .  j a v  a  2 s .  com*/
@SuppressWarnings("unchecked")
public static Class<? extends IBindableDescriptor> getDescriptorClass(Class<?> clazz) {
    if (clazz.getAnnotation(Bindable.class) == null)
        throw new IllegalArgumentException("Class not marked with @Bindable: " + clazz.getName());

    ClassLoader cl = clazz.getClassLoader();
    String descriptorClassName = getDescriptorClassName(clazz.getName());
    try {
        return (Class<? extends IBindableDescriptor>) Class.forName(descriptorClassName, true, cl);
    } catch (ClassNotFoundException e) {
        throw new NoClassDefFoundError("Descriptor class not found: " + descriptorClassName);
    }
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

private static <T> T newProxy(Class<T> interfaceType, InvocationHandler handler) {
    Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(), new Class<?>[] { interfaceType },
            handler);/*from   w w w  . j  a v a  2s. c  o m*/
    return interfaceType.cast(object);
}

From source file:com.npower.dm.util.DMUtil.java

/**
 * Format a string buffer containing the Class, Interfaces, CodeSource, and
 * ClassLoader information for the given object clazz.
 * /*from  w  ww  . j av  a2  s  . c om*/
 * @param clazz
 *          the Class
 * @param results,
 *          the buffer to write the info to
 */
public static void displayClassInfo(Class<?> clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
        results.append("\n.." + parent);
        URL[] urls = getClassLoaderURLs(parent);
        int length = urls != null ? urls.length : 0;
        for (int u = 0; u < length; u++) {
            results.append("\n...." + urls[u]);
        }
        if (parent != null)
            parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null)
        results.append("\n++++CodeSource: " + clazzCS);
    else
        results.append("\n++++Null CodeSource");
    results.append("\nImplemented Interfaces:");
    Class<?>[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
        results.append("\n++" + ifaces[i]);
        ClassLoader loader = ifaces[i].getClassLoader();
        results.append("\n++++ClassLoader: " + loader);
        ProtectionDomain pd = ifaces[i].getProtectionDomain();
        CodeSource cs = pd.getCodeSource();
        if (cs != null)
            results.append("\n++++CodeSource: " + cs);
        else
            results.append("\n++++Null CodeSource");
    }
}

From source file:org.psikeds.common.config.ServletContextProxy.java

private static ClassLoader getClassloader(final Class<? extends ServletContext> clazz) {
    // get classloader from class (might eventually not work in some j2ee
    // environments)
    final ClassLoader loader = clazz == null ? null : clazz.getClassLoader();
    // fallback to classloader of creator of current thread
    return loader == null ? Thread.currentThread().getContextClassLoader() : loader;
}

From source file:com.groupon.jenkins.util.ResourceUtils.java

private static String getTemplateFile(Class<?> resourceClass, String resourceName) {
    while (resourceClass != Object.class && resourceClass != null) {
        String name = resourceClass.getName().replace('.', '/').replace('$', '/') + "/" + resourceName;
        if (resourceClass.getClassLoader().getResource(name) != null)
            return '/' + name;
        resourceClass = resourceClass.getSuperclass();
    }//from w w w . jav  a  2  s  .  co  m
    return null;
}

From source file:gov.nih.nci.ncicb.cadsr.common.util.ObjectFactory.java

/**
 * Load a class for the specified name and scope.
 * In the cases when the active ClassLoader is null, we use
 *  Class.forName(), otherwise ClassLoader.loadClass() is used
 *///from  ww w .ja  va  2  s  .c om
public static Class forName(Class scope, String className) throws ClassNotFoundException {
    ClassLoader loader = null;

    try {
        loader = Thread.currentThread().getContextClassLoader();
    } // end try
    catch (Exception e) {
        loader = scope.getClassLoader();
    } // end catch

    return (loader != null) ? loader.loadClass(className) : Class.forName(className);
}

From source file:Which4J.java

/**
 * Search the current classloader for the given classname.
 * /*from   w w  w.j a va 2  s.c  o  m*/
 * Equivalent to calling which( Class clazz, Which4J.class.getClassLoader ).
 * 
 * @param clazz the class object to search for
 * @return the source location of the resource, or null if it wasn't found
 */
public static String which(Class clazz) {
    return which(clazz, clazz.getClassLoader());
}

From source file:com.almende.eve.agent.AgentProxyFactory.java

/**
 * Gen proxy.//from   w  ww.  ja v a  2 s  .  c o  m
 * 
 * @param <T>
 *            the generic type
 * @param sender
 *            the sender
 * @param receiverUrl
 *            the receiver url
 * @param proxyInterface
 *            the interface this proxy implements
 * @return the t
 */
@SuppressWarnings("unchecked")
public static <T> T genProxy(final Agent sender, final URI receiverUrl, final Class<T> proxyInterface) {
    // http://docs.oracle.com/javase/1.4.2/docs/guide/reflection/proxy.html
    final T proxy = (T) Proxy.newProxyInstance(proxyInterface.getClassLoader(), new Class[] { proxyInterface },
            new InvocationHandler() {

                private Map<Method, Boolean> cache = new HashMap<Method, Boolean>();

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args) {
                    boolean doSync = true;
                    if (cache.containsKey(method)) {
                        doSync = cache.get(method);
                    } else {
                        AnnotatedClass clazz = AnnotationUtil.get(proxyInterface);
                        if (clazz != null) {
                            List<AnnotatedMethod> list = clazz.getMethods(method.getName());
                            for (AnnotatedMethod m : list) {
                                if (m.getAnnotation(NoReply.class) != null) {
                                    doSync = false;
                                }
                            }
                            if (doSync && method.getReturnType().equals(void.class)
                                    && clazz.getAnnotation(NoReply.class) != null) {
                                doSync = false;
                            }
                        }
                        cache.put(method, doSync);
                    }
                    SyncCallback<JsonNode> callback = null;
                    if (doSync) {
                        callback = new SyncCallback<JsonNode>() {
                        };
                    }
                    try {
                        sender.call(receiverUrl, method, args, callback);
                    } catch (final IOException e) {
                        throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e);
                    }
                    if (callback != null) {
                        try {
                            return TypeUtil.inject(callback.get(), method.getGenericReturnType());
                        } catch (final Exception e) {
                            throw new JSONRPCException(CODE.REMOTE_EXCEPTION, e.getLocalizedMessage(), e);
                        }
                    }
                    return null;
                }
            });
    return proxy;
}