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.google.code.ddom.commons.cl.ClassLoaderLocal.java

private static Map<ClassLoaderLocal<?>, Object> getClassLoaderLocalMap(ClassLoader cl) {
    if (cl == ClassLoaderLocal.class.getClassLoader()) {
        return ClassLoaderLocalMapHolder.locals;
    } else {/*w  w w. j a  va2  s .  c o  m*/
        Class<?> holderClass;
        try {
            holderClass = cl.loadClass(holderClassName);
            if (holderClass.getClassLoader() != cl) {
                holderClass = null;
            }
        } catch (ClassNotFoundException ex) {
            holderClass = null;
        }
        if (holderClass == null) {
            try {
                holderClass = (Class<?>) defineClassMethod.invoke(cl, holderClassName, holderClassDef, 0,
                        holderClassDef.length);
            } catch (Exception ex) {
                // TODO: can we get here? maybe if two threads call getClassLoaderLocalMap concurrently?
                throw new Error(ex);
            }
        }
        Field field;
        try {
            field = holderClass.getDeclaredField("locals");
        } catch (NoSuchFieldException ex) {
            throw new NoSuchFieldError(ex.getMessage());
        }
        try {
            return (Map<ClassLoaderLocal<?>, Object>) field.get(0);
        } catch (IllegalAccessException ex) {
            throw new Error(ex);
        }
    }
}

From source file:com.singular.utils.FileUtils.java

/**
 * Taken from apache hadoop project.//  w  w w.j  av  a  2  s  .c  o m
 * Apache 2.0 license.
 *
 * @param className
 * @return
 */
public static String findContainingJar(Class className) {
    ClassLoader loader = className.getClassLoader();
    String classFile = className.getName().replaceAll("\\.", "/") + ".class";

    try {
        for (Enumeration 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 = toReturn.replaceAll("\\+", "%2B");
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.agiso.core.lang.util.ClassUtils.java

public static String locate(Class<?> c) /*throws ClassNotFoundException*/ {
    return locate(c, c.getClassLoader());
}

From source file:ml.shifu.guagua.hadoop.util.HDPUtils.java

@SuppressWarnings("rawtypes")
public static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    if (loader == null) {
        loader = Thread.currentThread().getContextClassLoader();
    }/*w  ww.  j  a  va2s.  c o  m*/
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {
        Enumeration<URL> itr = null;
        // Try to find the class in registered jars
        if (loader instanceof URLClassLoader) {
            itr = ((URLClassLoader) loader).findResources(class_file);
        }
        // Try system classloader if not URLClassLoader or no resources found in URLClassLoader
        if (itr == null || !itr.hasMoreElements()) {
            itr = loader.getResources(class_file);
        }
        for (; 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());
                }
                // 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("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.eclipse.wb.core.gef.MatchingEditPartFactory.java

private static EditPart createEditPart0(Object model, Class<?> modelClass, String partClassName) {
    try {// w ww  . j  av  a  2 s.com
        ClassLoader classLoader = modelClass.getClassLoader();
        Class<?> partClass = classLoader.loadClass(partClassName);
        // try all constructors
        for (Constructor<?> constructor : partClass.getConstructors()) {
            try {
                return (EditPart) constructor.newInstance(model);
            } catch (Throwable e) {
                // ignore
            }
        }
    } catch (Throwable e) {
        // ignore
    }
    return null;
}

From source file:net.geoprism.context.ServerInitializer.java

@Request
private static void startup(List<ServerContextListenerInfo> infos) {
    for (ServerContextListenerInfo info : infos) {
        try {//from ww  w.j  a v a  2s .com

            Class<?> clazz = LoaderDecorator.load(info.getClassName());
            Object newInstance = clazz.newInstance();

            try {
                ServerContextListener listener = (ServerContextListener) newInstance;
                listener.startup();
            } catch (ClassCastException e) {
                log.error("ClassCastException initializer", e);

                Class<? extends Object> class1 = newInstance.getClass();
                ClassLoader loader1 = class1.getClassLoader();

                log.debug("New instance class : " + class1.hashCode());
                log.debug("New instance class loader: " + loader1.hashCode());

                Class<? extends Object> class2 = ServerContextListener.class;
                ClassLoader loader2 = class2.getClassLoader();

                log.debug("Interface class : " + class2.hashCode());
                log.debug("New instance class loader: " + loader2.hashCode());

                clazz.getMethod("startup").invoke(newInstance);
            }

            log.debug("COMLPETE: " + info.getClassName() + ".setup();");
        } catch (Exception e) {
            log.error(e);

            throw new ProgrammingErrorException(
                    "Unable to startup the server context listener [" + info.getClassName() + "]", e);
        }
    }
}

From source file:com.edmunds.autotest.ClassUtil.java

public static Object instanceClass(Class cls, String msg) {
    if (cls.isInterface()) {
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls }, NOOP_HANDLER);
    } else if (isStandardClass(cls) && hasDefaultConstructor(cls)) {
        try {/*from   w  w  w. j  a  v a  2  s . co m*/
            Constructor constructor = getDefaultConstructor(cls);
            constructor.setAccessible(true);

            return constructor.newInstance();

        } catch (InvocationTargetException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (InstantiationException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        } catch (IllegalAccessException e) {
            log.error(msg, e);
            throw new RuntimeException(msg, e);
        }
    }
    return null;
}

From source file:guru.qas.martini.i18n.MessageSources.java

public static MessageSource getMessageSource(Class c) {
    return INDEX.computeIfAbsent(c, r -> {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setFallbackToSystemLocale(true);
        source.setBundleClassLoader(c.getClassLoader());
        source.setBasename(c.getName());
        source.setUseCodeAsDefaultMessage(true);
        source.setCacheSeconds(-1);//  w  w  w. j av  a2  s  .c  o  m
        return source;
    });
}

From source file:net.geoprism.context.ServerInitializer.java

@Request
public static void destroy() {
    ServerContextListenerDocumentBuilder builder = new ServerContextListenerDocumentBuilder();
    List<ServerContextListenerInfo> infos = builder.read();

    Collections.reverse(infos);// w  ww .  ja va  2s. c  o  m

    for (ServerContextListenerInfo info : infos) {
        try {

            Class<?> clazz = LoaderDecorator.load(info.getClassName());
            Object newInstance = clazz.newInstance();

            try {
                ServerContextListener listener = (ServerContextListener) newInstance;
                listener.shutdown();
            } catch (ClassCastException e) {
                log.error("ClassCastException in ServerInitializer.shutdown", e);

                Class<? extends Object> class1 = newInstance.getClass();
                ClassLoader loader1 = class1.getClassLoader();

                log.debug("New instance class : " + class1.hashCode());
                log.debug("New instance class loader: " + loader1.hashCode());

                Class<? extends Object> class2 = ServerContextListener.class;
                ClassLoader loader2 = class2.getClassLoader();

                log.debug("Interface class : " + class2.hashCode());
                log.debug("New instance class loader: " + loader2.hashCode());

                clazz.getMethod("shutdown").invoke(newInstance);
            }

            log.debug("COMLPETE: " + info.getClassName() + ".shutdown();");
        } catch (Exception e) {
            log.error(e);

            throw new ProgrammingErrorException(
                    "Unable to shutdown the server context listener [" + info.getClassName() + "]", e);
        }
    }
}

From source file:org.drombler.commons.client.util.ResourceBundleUtils.java

public static String getClassResourceStringPrefixed(Class<?> type, String resourceKey) {
    return getResourceStringPrefixed(resourceKey, type.getPackage().getName(), type.getSimpleName(),
            type.getClassLoader());
}