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:me.tfeng.toolbox.avro.AvroHelper.java

public static Protocol getProtocol(Class<?> interfaceClass) {
    return new SpecificData(interfaceClass.getClassLoader()).getProtocol(interfaceClass);
}

From source file:de.cebitec.mgx.seqstorage.ReaderFactoryTest.java

private static File copyTestData(Class clazz, String uri, File targetDir, String targetName) throws Exception {
    File f = new File(targetDir.getAbsolutePath() + File.separator + targetName);
    try (BufferedInputStream is = new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(uri))) {
        f.deleteOnExit();// www  . j a v  a  2s .  c o m
        try (FileOutputStream fos = new FileOutputStream(f)) {
            byte[] buffer = new byte[1024];
            int bytesRead = is.read(buffer);
            while (bytesRead >= 0) {
                fos.write(buffer, 0, bytesRead);
                bytesRead = is.read(buffer);
            }
        }
    }
    return f;
}

From source file:edu.umich.flowfence.client.Sealed.java

public static <T> Sealed<T> wrap(IHandle handle, Class<T> refClass) {
    try {/*w  ww .jav a2s  .com*/
        ParamInfo pi = handle.getParamInfo();
        Class<?> declaredClass = pi.getType(refClass.getClassLoader());
        if (!ClassUtils.isAssignable(declaredClass, refClass, true)) {
            throw new ClassCastException("Can't assign " + declaredClass + " to reference of type " + refClass);
        }
        return new Sealed<>(handle);
    } catch (Exception e) {
        ParceledThrowable.throwUnchecked(e);
        return null;
    }
}

From source file:org.eclipse.wb.tests.designer.core.TestBundle.java

public static InputStream getClassBytes(Class<?> clazz) {
    return getClassBytes(clazz.getClassLoader(), clazz.getName());
}

From source file:core.service.proxy.ServiceProxy.java

/**
 * new instance/*from   w ww  . ja  v  a  2 s .co m*/
 * 
 * @param serviceInterface
 * @param executor
 * @return
 */
public static Object newInstance(Class serviceInterface, ApplicationContext context,
        ClientServiceSession session) {
    return java.lang.reflect.Proxy.newProxyInstance(serviceInterface.getClassLoader(),
            new Class[] { serviceInterface }, new ServiceProxy(serviceInterface, context, session));
}

From source file:com.linecorp.armeria.server.docs.FunctionInfo.java

static FunctionInfo of(Method method, Map<Class<?>, ? extends TBase<?, ?>> sampleRequests,
        @Nullable String namespace, Map<String, String> docStrings) throws ClassNotFoundException {
    requireNonNull(method, "method");

    final String methodName = method.getName();

    final Class<?> serviceClass = method.getDeclaringClass().getDeclaringClass();
    final String serviceName = serviceClass.getName();
    final ClassLoader classLoader = serviceClass.getClassLoader();

    @SuppressWarnings("unchecked")
    Class<? extends TBase<?, ?>> argsClass = (Class<? extends TBase<?, ?>>) Class
            .forName(serviceName + '$' + methodName + "_args", false, classLoader);
    String sampleJsonRequest;/*from w w  w .  ja  v  a 2 s . c  o  m*/
    TBase<?, ?> sampleRequest = sampleRequests.get(argsClass);
    if (sampleRequest == null) {
        sampleJsonRequest = "";
    } else {
        TSerializer serializer = new TSerializer(ThriftProtocolFactories.TEXT);
        try {
            sampleJsonRequest = serializer.toString(sampleRequest, StandardCharsets.UTF_8.name());
        } catch (TException e) {
            throw new IllegalArgumentException(
                    "Failed to serialize to a memory buffer, this shouldn't ever happen.", e);
        }
    }

    @SuppressWarnings("unchecked")
    final FunctionInfo function = new FunctionInfo(namespace, methodName, argsClass,
            (Class<? extends TBase<?, ?>>) Class.forName(serviceName + '$' + methodName + "_result", false,
                    classLoader),
            (Class<? extends TException>[]) method.getExceptionTypes(), sampleJsonRequest, docStrings);
    return function;
}

From source file:com.ocpsoft.pretty.faces.util.ServiceLoader.java

/**
 * Creates a new service loader for the given service type and class loader.
 * //from  w w  w  .  j  ava2 s .  c om
 * @param service The interface or abstract class representing the service
 * @param loader The class loader to be used to load provider-configuration
 *           files and provider classes, or null if the system class loader
 *           (or, failing that, the bootstrap class loader) is to be used
 * @return A new service loader
 */
public static <S> ServiceLoader<S> load(Class<S> service, ClassLoader loader) {
    if (loader == null) {
        loader = service.getClassLoader();
    }
    return new ServiceLoader<S>(service, loader);
}

From source file:org.apache.axis2.jaxws.util.ClassLoaderUtils.java

/**
 * @return ClassLoader//  w ww  .j  a v a 2 s .c o  m
 */
public static ClassLoader getClassLoader(final Class cls) {
    ClassLoader cl = null;
    try {
        cl = (ClassLoader) AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws ClassNotFoundException {
                return cls.getClassLoader();
            }
        });
    } catch (PrivilegedActionException e) {
        if (log.isDebugEnabled()) {
            log.debug("Exception thrown from AccessController: " + e);
        }
        throw ExceptionFactory.makeWebServiceException(e.getException());
    }

    return cl;
}

From source file:com.yunrang.hadoop.app.utils.CustomizedUtil.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.
 * /*from   w w  w  .ja v  a  2s .c o m*/
 * @param my_class the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
public 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:jetbrains.exodus.util.ForkSupportIO.java

public static List<String> getClasspath(Class cls) {
    List<String> classpath = new ArrayList<>();
    URL[] urls = ((URLClassLoader) cls.getClassLoader()).getURLs();
    for (URL url : urls) {
        File f;/*  ww  w.  j  a  v  a 2s .  c om*/
        try {
            f = new File(url.toURI());
        } catch (URISyntaxException e) {
            f = new File(url.getPath());
        }

        classpath.add(f.getAbsolutePath());
    }

    return classpath;
}