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.freetmp.common.util.ClassUtils.java

public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
    Assert.notNull(clazz, "Class must not be null");
    try {//from w  w  w  .j a  v a2 s.c  o  m
        ClassLoader target = clazz.getClassLoader();
        if (target == null) {
            return true;
        }
        ClassLoader cur = classLoader;
        if (cur == target) {
            return true;
        }
        while (cur != null) {
            cur = cur.getParent();
            if (cur == target) {
                return true;
            }
        }
        return false;
    } catch (SecurityException ex) {
        // Probably from the system ClassLoader - let's consider it safe.
        return true;
    }
}

From source file:edu.sampleu.admin.EdocLiteXmlIngesterBase.java

protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception {
    String classPath = clazz.getName().replace(".", "/") + ".class";
    URL dirUrl = clazz.getClassLoader().getResource(classPath);

    if (!"jar".equals(dirUrl.getProtocol())) {
        throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl);
    }// www. j av  a 2 s .  co  m

    String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file
    JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
    Enumeration<JarEntry> entries = jar.entries();
    Set<String> result = new HashSet<String>();

    while (entries.hasMoreElements()) {
        String entry = entries.nextElement().getName();
        if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories
            result.add(entry);
        }
    }

    return result.toArray(new String[result.size()]);
}

From source file:org.eclipse.skalli.core.configuration.ConfigurationComponent.java

private XStream getXStream(Class<?> customizationClass) {
    XStream xstream = new XStream();
    ClassLoader classLoader = customizationClass.getClassLoader();
    if (classLoader != null) {
        xstream.setClassLoader(new CompositeEntityClassLoader(Collections.singleton(classLoader)));
    }//from  ww  w. j  a v  a  2s  .c  o  m
    return xstream;
}

From source file:de.uni.bremen.monty.moco.ast.ASTBuilderTest.java

private String getFileContent(String fileName) throws URISyntaxException, IOException {
    Class<CompileTestProgramsTest> aClass = CompileTestProgramsTest.class;
    ClassLoader classLoader = aClass.getClassLoader();
    File file = new File(classLoader.getResource(fileName).toURI());
    return FileUtils.readFileToString(file);
}

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

/**
 * Create a proxy for the indicated type.
 * @param handler The handler// w w w  .  ja va 2s  .  com
 * @param type The type, should to be a concrete class type
 * @return The proxy
 */
@SuppressWarnings("unchecked")
private <T> T newProxyForConcreteClass(org.springframework.cglib.proxy.Callback handler, Class<T> type) {
    Enhancer enhancer;

    Assert.isTrue(!Modifier.isAbstract(type.getModifiers()), "The type should to be a concrete class");

    enhancer = new Enhancer();
    enhancer.setSuperclass(type);
    enhancer.setClassLoader(type.getClassLoader());
    enhancer.setCallback(handler);
    return (T) enhancer.create();
}

From source file:org.corfudb.runtime.protocols.AsyncPooledThriftClient.java

/**
 * Gets a client instance that implements the AsyncIface interface that
 * connects to the given connection string.
 *
 * @param <T>//w  ww. ja  va2  s .c  o m
 * @param asyncIfaceClass
 *          the AsyncIface interface to pool.
 * @param connectionStr
 *          the connection string.
 * @return the client instance.
 */
@SuppressWarnings("unchecked")
public <T> T getClient(final Class<T> asyncIfaceClass) {
    return (T) Proxy.newProxyInstance(asyncIfaceClass.getClassLoader(), new Class[] { asyncIfaceClass },
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return execute(new AsyncCall(asyncIfaceClass, method, args, _connection));
                }
            });
}

From source file:haven.Utils.java

public static Resource myres(Class<?> c) {
    ClassLoader cl = c.getClassLoader();
    if (cl instanceof Resource.ResClassLoader) {
        return (((Resource.ResClassLoader) cl).getres());
    } else {/*from  www.ja  v a2s .co  m*/
        return (null);
    }
}

From source file:org.apache.hadoop.sqoop.orm.CompilationManager.java

private String findJarForClass(Class<? extends Object> classObj) {
    ClassLoader loader = classObj.getClassLoader();
    String classFile = classObj.getName().replaceAll("\\.", "/") + ".class";
    try {//w w  w .  j av  a  2  s .  c om
        for (Enumeration<URL> itr = loader.getResources(classFile); itr.hasMoreElements();) {
            URL 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) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:io.s4.meter.controller.RestletCommunicator.java

private void sendClassInternal(Class<?> clazz, ClientResource resource) throws IOException {

    String filename = clazz.getName().replace('.', File.separatorChar) + ".class";
    InputStream in = null;/*ww  w  . j ava 2  s  .c om*/
    in = clazz.getClassLoader().getResourceAsStream(filename);

    if (in == null) {
        // System.out.println("Could not find resource: " + filename);
        logger.error("Could not find resource: " + filename);
    }
    byte[] classBytes = IOUtils.toByteArray(in);

    resource.post((Object) classBytes);
    logger.trace("POST: " + resource.getReference() + " by resource " + resource.toString());
}

From source file:org.crazydog.util.spring.ClassUtils.java

/**
 * Check whether the given class is cache-safe in the given context,
 * i.e. whether it is loaded by the given ClassLoader or a parent of it.
 * @param clazz the class to analyze// ww w  .  j  a  v a  2  s .c  o  m
 * @param classLoader the ClassLoader to potentially cache metadata in
 */
public static boolean isCacheSafe(Class<?> clazz, ClassLoader classLoader) {
    org.springframework.util.Assert.notNull(clazz, "Class must not be null");
    try {
        ClassLoader target = clazz.getClassLoader();
        if (target == null) {
            return true;
        }
        ClassLoader cur = classLoader;
        if (cur == target) {
            return true;
        }
        while (cur != null) {
            cur = cur.getParent();
            if (cur == target) {
                return true;
            }
        }
        return false;
    } catch (SecurityException ex) {
        // Probably from the system ClassLoader - let's consider it safe.
        return true;
    }
}