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.hadoop.yarn.ipc.ProtoOverHadoopRpcEngine.java

@Override
@SuppressWarnings("unchecked")
public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {

    return new ProtocolProxy<T>(protocol, (T) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout)), false);
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloaderTest.java

@Test
public void testLoadClassFindClass() throws ClassNotFoundException, IOException, KettleFileException {
    String canonicalName = ShimBridgingClassloader.class.getCanonicalName();
    FileObject myFile = KettleVFS.getFileObject("ram://testLoadClassFindClass");
    try (FileObject fileObject = myFile) {
        try (OutputStream outputStream = fileObject.getContent().getOutputStream(false)) {
            IOUtils.copy(/*from ww w. j av a2  s  . c om*/
                    getClass().getClassLoader().getResourceAsStream(canonicalName.replace(".", "/") + ".class"),
                    outputStream);
        }
        String packageName = ShimBridgingClassloader.class.getPackage().getName();
        when(bundleWiring.findEntries("/" + packageName.replace(".", "/"),
                ShimBridgingClassloader.class.getSimpleName() + ".class", 0))
                        .thenReturn(Arrays.asList(fileObject.getURL()));
        when(parentClassLoader.loadClass(anyString(), anyBoolean())).thenAnswer(new Answer<Class<?>>() {
            @Override
            public Class<?> answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                return new ShimBridgingClassloader.PublicLoadResolveClassLoader(getClass().getClassLoader())
                        .loadClass((String) arguments[0], (boolean) arguments[1]);
            }
        });
        Class<?> shimBridgingClassloaderClass = shimBridgingClassloader.loadClass(canonicalName, true);
        assertEquals(canonicalName, shimBridgingClassloaderClass.getCanonicalName());
        assertEquals(shimBridgingClassloader, shimBridgingClassloaderClass.getClassLoader());
        assertEquals(packageName, shimBridgingClassloaderClass.getPackage().getName());
        Class<?> shimBridgingClassloaderClass2 = shimBridgingClassloader.loadClass(canonicalName, false);
        assertEquals(shimBridgingClassloaderClass, shimBridgingClassloaderClass2);
    } finally {
        myFile.delete();
    }
}

From source file:com.liferay.httpservice.internal.servlet.BundleServletContextTest.java

protected void mockBundleWiring() {
    when(_bundle.adapt(BundleWiring.class)).thenReturn(_bundleWiring);

    Class<?> clazz = getClass();

    when(_bundleWiring.getClassLoader()).thenReturn(clazz.getClassLoader());
}

From source file:com.greenpepper.runner.ant.AntTaskRunner.java

private Object createRunner(ClassLoader classLoader, CommandLineRunnerMirror.CommandLineLogger logger,
        CommandLineRunnerMirror.CommandLineMonitor monitor) {
    try {//from w w w  . j  a va2 s .c  o m
        Class<?> runnerClass = classLoader.loadClass("com.greenpepper.runner.ant.CommandLineRunnerMirrorImpl");

        if (runnerClass.getClassLoader() != classLoader) {
            throw new BuildException("Overdelegating loader", getLocation());
        }

        Constructor runnerCtr = runnerClass.getConstructor(Object.class, Object.class);

        return runnerCtr.newInstance(logger, monitor);
    } catch (Exception ex) {
        throw new BuildException(ex, getLocation());
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the {@link ClassLoader} that was used to load given {@link Class}. Always return not
 *         <code>null</code> value, even if {@link Class} was loaded using bootstrap
 *         {@link ClassLoader}.//w w w  . j  av a 2s. com
 */
public static ClassLoader getClassLoader(Class<?> clazz) {
    ClassLoader classLoader = clazz.getClassLoader();
    if (classLoader == null) {
        classLoader = ClassLoader.getSystemClassLoader();
    }
    return classLoader;
}

From source file:org.apache.hadoop.hbase.ipc.SecureRpcEngine.java

/**
 * Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address.
 *
 * @param protocol interface/*ww  w. j ava 2s . c  o m*/
 * @param clientVersion version we are expecting
 * @param addr remote address
 * @param conf configuration
 * @return proxy
 * @throws java.io.IOException e
 */
@Override
public <T extends VersionedProtocol> T getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr,
        Configuration conf, int rpcTimeout) throws IOException {
    if (this.client == null) {
        throw new IOException("Client must be initialized by calling setConf(Configuration)");
    }

    T proxy = (T) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(this.client, protocol, addr, User.getCurrent(), HBaseRPC.getRpcTimeout(rpcTimeout)));
    /*
     * TODO: checking protocol version only needs to be done once when we setup a new
     * SecureClient.Connection.  Doing it every time we retrieve a proxy instance is resulting
     * in unnecessary RPC traffic.
     */
    long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion);
    if (serverVersion != clientVersion) {
        throw new HBaseRPC.VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }
    return proxy;
}

From source file:org.atricore.idbus.kernel.planning.jbpm.OsgiProcessFragmentRegistryApplicationContext.java

/**
 * Load a given resource. <p/> This method will try to load the resource
 * using the following methods (in order):
 * <ul>/*from ww w . ja v  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
 */
private 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));
    }

    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:org.apache.servicemix.platform.testing.support.SmxPlatform.java

private Set<String> getJars(Class... classes) {
    Set<String> jars = new HashSet<String>();
    for (Class cl : classes) {
        String name = cl.getName().replace('.', '/') + ".class";
        URL url = (cl.getClassLoader() != null ? cl.getClassLoader() : getClass().getClassLoader())
                .getResource(name);// w  w w .  ja v a2s .c  o  m
        String path = url.toString();
        if (path.startsWith("jar:")) {
            path = path.substring(0, path.indexOf('!'));
        } else {
            path = path.substring(0, path.indexOf(name));
        }
        jars.add(path);
    }
    return jars;
}

From source file:org.apache.hadoop.ipc.ProtobufRpcEngine.java

@Override
public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy(ConnectionId connId, Configuration conf,
        SocketFactory factory) throws IOException {
    Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class;
    return new ProtocolProxy<ProtocolMetaInfoPB>(protocol,
            (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
                    new Invoker(protocol, connId, conf, factory)),
            false);/*from   w ww . j  a v a  2s . c  om*/
}

From source file:org.resthub.rpc.AMQPProxyFactory.java

/**
 * Creates a new proxy from the specified interface.
 * @param api the interface//  w  w  w  . j a  va 2  s.c o m
 * @return the proxy to the object with the specified interface
 */
@SuppressWarnings("unchecked")
public <T> T create(Class<T> api) {
    if (null == api || !api.isInterface()) {
        throw new IllegalArgumentException("Parameter 'api' is required");
    }
    this.serviceInterface = api;
    this.afterPropertiesSet();
    AMQPProxy handler = new AMQPProxy(this);
    return (T) Proxy.newProxyInstance(api.getClassLoader(), new Class[] { api }, handler);
}