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.cryptomator.ui.Cryptomator.java

private static void addOsxFileOpenHandler() {
    /*/*from w ww .  j  av a 2 s.co m*/
     * On OSX we're in an awkward position. We need to register a handler in the main thread of this application. However, we can't
     * even pass objects to the application, so we're forced to use a static CompletableFuture for the handler, which actually opens
     * the file in the application.
     * 
     * Code taken from https://github.com/axet/desktop/blob/master/src/main/java/com/github/axet/desktop/os/mac/AppleHandlers.java
     */
    try {
        final Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
        final Class<?> openFilesHandlerClass = Class.forName("com.apple.eawt.OpenFilesHandler");
        final Method getApplication = applicationClass.getMethod("getApplication");
        final Object application = getApplication.invoke(null);
        final Method setOpenFileHandler = applicationClass.getMethod("setOpenFileHandler",
                openFilesHandlerClass);

        final ClassLoader openFilesHandlerClassLoader = openFilesHandlerClass.getClassLoader();
        final OpenFilesHandlerClassHandler openFilesHandlerHandler = new OpenFilesHandlerClassHandler();
        final Object openFilesHandlerObject = Proxy.newProxyInstance(openFilesHandlerClassLoader,
                new Class<?>[] { openFilesHandlerClass }, openFilesHandlerHandler);

        setOpenFileHandler.invoke(application, openFilesHandlerObject);
    } catch (ReflectiveOperationException | RuntimeException e) {
        // Since we're trying to call OS-specific code, we'll just have
        // to hope for the best.
        LOG.error("exception adding OSX file open handler", e);
    }
}

From source file:org.beangle.model.persist.hibernate.internal.ClassUtils.java

/**
 * Returns the classloader for the given class. This method deals with JDK
 * classes which return by default, a null classloader.
 * /*from   ww w  . j av  a  2 s. co  m*/
 * @param clazz
 * @return
 */
public static ClassLoader getClassLoader(Class<?> clazz) {
    Validate.notNull(clazz);
    ClassLoader loader = clazz.getClassLoader();
    return (loader == null ? ClassLoader.getSystemClassLoader() : loader);
}

From source file:ReflectionHelper.java

public static Class<?> loadClass(String name, Class<?> caller) throws ClassNotFoundException {
    try {/*  ww  w .j  a va2 s . c o  m*/
        //try context classloader, if fails try caller classloader
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if (loader != null) {
            return loader.loadClass(name);
        }
    } catch (ClassNotFoundException e) {
        //trying caller classloader
        if (caller == null) {
            throw e;
        }
    }
    return Class.forName(name, true, caller.getClassLoader());
}

From source file:com.eryansky.common.utils.io.FileUtil.java

@SuppressWarnings("rawtypes")
public static String getAppPath(Class cls) {
    // ??//from   ww  w  . j a  v  a  2  s  .  c o m
    if (cls == null)
        throw new java.lang.IllegalArgumentException("???");
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax."))
            throw new java.lang.IllegalArgumentException("????");
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0)
            path = packName + "/";
        else {// ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    java.net.URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1)
        realPath = realPath.substring(pos + 5);
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!"))
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    /*------------------------------------------------------------ 
     ClassLoadergetResourceutf-8?? 
      ??? 
      URLDecoderdecode? 
      ? 
    -------------------------------------------------------------*/
    try {
        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    System.out.println("realPath----->" + realPath);
    return realPath;
}

From source file:com.wavemaker.runtime.server.ServerUtils.java

/**
 * Get a list of methods to be exposed to the client. This will obey restrictions from {@link ExposeToClient} and
 * {@link HideFromClient}./* w w  w. j  a v  a  2s.  c om*/
 * 
 * @param klass The class to examine.
 * @return A list of methods to expose to the client in the specified class.
 */
@SuppressWarnings("unchecked")
public static List<Method> getClientExposedMethods(Class<?> klass) {

    List<Method> allMethods = ClassUtils.getPublicMethods(klass);
    List<Method> ret = new ArrayList<Method>(allMethods.size());
    ClassLoader cl = klass.getClassLoader();

    Class<Annotation> hideFromClient = (Class<Annotation>) ClassLoaderUtils
            .loadClass(HideFromClient.class.getCanonicalName(), cl);
    Class<Annotation> exposeToClient = (Class<Annotation>) ClassLoaderUtils
            .loadClass(ExposeToClient.class.getCanonicalName(), cl);

    if (klass.getAnnotation(hideFromClient) != null) {
        for (Method meth : allMethods) {
            if (meth.getAnnotation(exposeToClient) != null) {
                ret.add(meth);
            }
        }
    } else {
        for (Method meth : allMethods) {
            if (meth.getAnnotation(hideFromClient) == null) {
                ret.add(meth);
            }
        }
    }

    return ret;
}

From source file:org.eclipse.wb.internal.core.xml.model.description.rules.CreatePropertiesPropertyDescriptorRule.java

private static Class<?> resolvePropertyType(ComponentDescription componentDescription, Method setMethod) {
    Class<?> propertyType = setMethod.getParameterTypes()[0];
    final Type genericPropertyType = setMethod.getGenericParameterTypes()[0];
    if (genericPropertyType instanceof TypeVariable<?>) {
        final Class<?> declaringClass = setMethod.getDeclaringClass();
        final Class<?> actualClass = componentDescription.getComponentClass();
        return ExecutionUtils.runObjectIgnore(new RunnableObjectEx<Class<?>>() {
            public Class<?> runObject() throws Exception {
                String typeName = GenericsUtils.getTypeName(
                        GenericTypeResolver.superClass(GenericTypeResolver.EMPTY, actualClass, declaringClass),
                        genericPropertyType);
                return actualClass.getClassLoader().loadClass(typeName);
            }//from  ww w  . j av a 2s  . c om
        }, propertyType);
    }
    return propertyType;
}

From source file:com.eryansky.common.utils.io.FileUtils.java

@SuppressWarnings("rawtypes")
public static String getAppPath(Class cls) {
    // ??//from  ww w .j  a v  a2s.c o  m
    if (cls == null)
        throw new IllegalArgumentException("???");
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax."))
            throw new IllegalArgumentException("????");
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0)
            path = packName + "/";
        else {// ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    java.net.URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1)
        realPath = realPath.substring(pos + 5);
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!"))
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    /*------------------------------------------------------------ 
     ClassLoadergetResourceutf-8?? 
      ??? 
      URLDecoderdecode? 
      ? 
    -------------------------------------------------------------*/
    try {
        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    System.out.println("realPath----->" + realPath);
    return realPath;
}

From source file:Loader.java

public static URL getResource(Class loadClass, String name, boolean checkParents)
        throws ClassNotFoundException {
    URL url = null;//from   w  ww.ja  va2s  .com
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    while (url == null && loader != null) {
        url = loader.getResource(name);
        loader = (url == null && checkParents) ? loader.getParent() : null;
    }

    loader = loadClass == null ? null : loadClass.getClassLoader();
    while (url == null && loader != null) {
        url = loader.getResource(name);
        loader = (url == null && checkParents) ? loader.getParent() : null;
    }

    if (url == null) {
        url = ClassLoader.getSystemResource(name);
    }

    return url;
}

From source file:org.dhatim.util.ClassUtil.java

public static List<URL> getResources(String resourcePath, Class<?> caller) throws IOException {
    return getResources(resourcePath, caller.getClassLoader());
}

From source file:org.mrgeo.utils.HadoopUtils.java

public static String findContainingJar(Class clazz) {
    ClassLoader loader = clazz.getClassLoader();
    String classFile = clazz.getName().replaceAll("\\.", "/") + ".class";
    try {//w ww .ja  v  a 2  s  .  c  om
        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 = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}