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:com.chinamobile.bcbsp.util.BSPJob.java

/**
 * Find the BC-BSP application jar of the job.
 * @param myClass//from w  w  w  .  j av  a2s .c  o  m
 *        The BC-BSP application jarFileClass of the job.
 * @return The name of the jar.
 */
private static String findContainingJar(Class<?> myClass) {
    ClassLoader loader = myClass.getClassLoader();
    String classFile = myClass.getName().replaceAll("\\.", "/") + ".class";
    try {
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL url = itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        LOG.error("[findContainingJar]", e);
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.eclipse.virgo.kernel.userregion.internal.equinox.EquinoxOsgiFrameworkTests.java

@Test
public void testLoadClassAndGetClassLoader() throws Exception {
    Bundle bundle = installSpringCore(this.framework);
    assertEquals("incorrect bundle loaded", "org.springframework.core", bundle.getSymbolicName());
    Class<?> cls = bundle.loadClass("org.springframework.core.JdkVersion");
    assertNotNull(cls);/*  w  ww .  ja  v  a  2 s  .  c o  m*/
    assertTrue(cls.getClassLoader() instanceof KernelBundleClassLoader);
    assertTrue("classloader is screwed", cls.getClassLoader().toString().contains("org.springframework.core"));
}

From source file:org.apache.hama.ipc.AsyncRPC.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 * /*w  ww . j  av a 2  s. c  o  m*/
 * @param protocol
 * @param clientVersion
 * @param addr
 * @param ticket
 * @param conf
 * @param factory
 * @param rpcTimeout
 * @param connectionRetryPolicy
 * @param checkVersion
 * @return the proxy
 * @throws IOException
 */
public static VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion,
        InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory,
        int rpcTimeout, RetryPolicy connectionRetryPolicy, boolean checkVersion) throws IOException {

    final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout,
            connectionRetryPolicy);
    VersionedProtocol proxy = (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, invoker);

    if (checkVersion) {
        checkVersion(protocol, clientVersion, proxy);
    }
    return proxy;
}

From source file:hudson.ClassicPluginStrategyTest.java

/**
 * Test finding resources under masking.
 * "foo1" plugin contains attribute of Mask-Classes: org.apache.http.
 *///from www .  j  a v a2s  . c  o  m
@LocalData
@Issue("JENKINS-27289")
public void testMaskResourceClassLoader() throws Exception {
    PluginWrapper pw = jenkins.getPluginManager().getPlugin("foo1");
    Class<?> clazz = pw.classLoader.loadClass("org.apache.http.impl.io.SocketInputBuffer");
    ClassLoader cl = clazz.getClassLoader();
    URL url = cl.getResource("org/apache/http/impl/io/SocketInputBuffer.class");
    assertNotNull(url);
    assertTrue("expected to find the class from foo1 plugin", url.toString().contains("plugins/foo1"));
}

From source file:com.navercorp.pinpoint.profiler.instrument.classloading.Java9DefineClassTest.java

@Test
public void defineClass() throws ClassNotFoundException, IOException {
    URL location = CodeSourceUtils.getCodeLocation(Logger.class);
    logger.debug("location:{}", location);

    URL[] empty = {};/*from   www .ja v a 2s  . com*/
    URLClassLoader classLoader = new URLClassLoader(empty, null);
    try {
        classLoader.loadClass(Logger.class.getName());
        Assert.fail();
    } catch (ClassNotFoundException ignore) {
    }

    String className = JavaAssistUtils.javaClassNameToJvmResourceName(Logger.class.getName());
    InputStream classStream = Logger.class.getClassLoader().getResourceAsStream(className);
    byte[] bytes = IOUtils.readFully(classStream, classStream.available());

    DefineClass defineClass = new Java9DefineClass();
    Class<?> defineClassSlf4jLogger = defineClass.defineClass(classLoader, Logger.class.getName(), bytes);
    Class<?> slf4jLogger = classLoader.loadClass(Logger.class.getName());

    Assert.assertSame(defineClassSlf4jLogger, slf4jLogger);
    Assert.assertSame(slf4jLogger.getClassLoader(), classLoader);

    Assert.assertNotSame(slf4jLogger.getClassLoader(), Logger.class.getClassLoader());

}

From source file:com.liferay.application.list.deploy.hot.test.LegacyPortletPanelAppHotDeployListenerTest.java

protected HotDeployEvent getHotDeployEvent(String location) throws Exception {

    Class<?> clazz = getClass();

    ClassLoader classLoader = clazz.getClassLoader();

    ResourceLoader resourceLoader = new TestResourceLoader(location, classLoader);

    ServletContext servletContext = new TestServletContext("/", resourceLoader);

    return new HotDeployEvent(servletContext, classLoader);
}

From source file:my.school.spring.beans.ProfilingBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class beanClazz = profilingClasses.get(beanName);
    if (beanClazz != null) {
        Object proxyInstance = Proxy.newProxyInstance(beanClazz.getClassLoader(), beanClazz.getInterfaces(),
                (Object proxy, Method method, Object[] args) -> {
                    LOG.info("Call for {}::{}", proxy.getClass().getName(), method.getName());
                    Object ret;// w  ww .  j a va  2 s  .  c o  m
                    if (profilingController.isEnabled()) {
                        long startTime = System.nanoTime();
                        ret = method.invoke(bean, args);
                        long endTime = System.nanoTime();
                        LOG.info("PROF:8150F577C514: {}", endTime - startTime);
                    } else {
                        ret = method.invoke(bean, args);
                    }
                    ret.getClass().getName();
                    return ret;
                });
        LOG.info("Creating a PROXY for {}: {} over target of class {} (Defined as: {})", beanName,
                proxyInstance.getClass().getName(), bean.getClass().getName(), beanClazz.getName());
        return proxyInstance;
    }
    return bean;
}

From source file:org.broadleafcommerce.common.extension.ExtensionManager.java

/**
 * Should take in a className that matches the ExtensionHandler interface being managed.
 * @param className/* ww  w  . j a v a  2  s . c o  m*/
 */
@SuppressWarnings("unchecked")
public ExtensionManager(Class<T> _clazz) {
    extensionHandler = (T) Proxy.newProxyInstance(_clazz.getClassLoader(), new Class[] { _clazz }, this);
}

From source file:com.nominanuda.hyperapi.HttpClientHyperApiFactory.java

public <T> T getInstance(String instanceHint, Class<? extends T> cl) {
    InvocationHandler handler = new HyperApiHttpInvocationHandler(cl, client,
            ifNull(uriPrefix, "") + ifNull(instanceHint, ""));
    Object p = Proxy.newProxyInstance(cl.getClassLoader(), new Class[] { cl }, handler);
    return cl.cast(p);
}

From source file:cat.albirar.framework.proxy.ProxyFactory.java

/**
 * Create a proxy for the indicated type.
 * @param handler The handler//from   w ww. j a  v a 2  s .c o m
 * @param type The type, should to be a interface type
 * @return The proxy
 */
@SuppressWarnings("unchecked")
private <T> T newProxyForInterface(java.lang.reflect.InvocationHandler handler, Class<T> type) {
    Assert.isTrue(type.isInterface(), "The type should to be an interface");
    return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, handler);
}