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.feilong.core.lang.ClassLoaderUtil.java

/**
 * ? {@link ClassLoader}.//from ww w.ja  va 2 s.  co  m
 * 
 * @param callingClass
 *            the calling class
 * @return  <code>callingClass</code> null, {@link NullPointerException}<br>
 * @see java.lang.Class#getClassLoader()
 */
private static ClassLoader getClassLoaderByClass(Class<?> callingClass) {
    Validate.notNull(callingClass, "callingClass can't be null!");
    ClassLoader classLoader = callingClass.getClassLoader();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[{}].getClassLoader():{}", callingClass.getSimpleName(), formatClassLoader(classLoader));
    }
    return classLoader;
}

From source file:org.apache.manifoldcf.core.i18n.Messages.java

/** Obtain a resource bundle given a class, bundle name, and locale.
*@return null if the resource bundle could not be found.
*///from ww  w .  j av  a 2  s . c  o m
public static ResourceBundle getResourceBundle(Class clazz, String bundleName, Locale locale) {
    ResourceBundle resources;
    ClassLoader classLoader = clazz.getClassLoader();
    try {
        resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
    } catch (MissingResourceException e) {
        complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '" + locale.toString()
                + "': " + e.getMessage() + "; trying " + locale.getLanguage(), e, bundleName, locale);
        // Try plain language next
        locale = new Locale(locale.getLanguage());
        try {
            resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
        } catch (MissingResourceException e2) {
            // Use English if we don't have a bundle for the current locale
            complainMissingBundle("Missing resource bundle '" + bundleName + "' for locale '"
                    + locale.toString() + "': " + e2.getMessage() + "; trying en_US", e2, bundleName, locale);
            locale = Locale.US;
            try {
                resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
            } catch (MissingResourceException e3) {
                complainMissingBundle("No backup en_US bundle found! " + e3.getMessage(), e3, bundleName,
                        locale);
                locale = new Locale(locale.getLanguage());
                try {
                    resources = ResourceBundle.getBundle(bundleName, locale, classLoader);
                } catch (MissingResourceException e4) {
                    complainMissingBundle("No backup en bundle found! " + e4.getMessage(), e4, bundleName,
                            locale);
                    return null;
                }
            }
        }
    }
    return resources;
}

From source file:org.identityconnectors.test.common.TestHelpers.java

/**
 * Method for convenient testing of local connectors.
 *//*from  ww  w  .j av a2 s . c  o m*/
public static APIConfiguration createTestConfiguration(Class<? extends Connector> clazz,
        final PropertyBag configData, String prefix) {
    URL url = clazz.getClassLoader().getResource("");
    Set<String> bundleContents = new HashSet<String>();

    try {
        URI relative = url.toURI();
        for (File file : FileUtils.listFiles(new File(url.toURI()), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE)) {
            bundleContents.add(relative.relativize(file.toURI()).getPath());
        }
        return getSpi().createTestConfiguration(clazz, bundleContents, configData, prefix);
    } catch (Exception e) {
        throw ConnectorException.wrap(e);
    }
}

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

static ServiceInfo of(Class<?> serviceClass, Iterable<EndpointInfo> endpoints,
        Map<Class<?>, ? extends TBase<?, ?>> sampleRequests) throws ClassNotFoundException {

    requireNonNull(serviceClass, "serviceClass");

    final String name = serviceClass.getName();

    final ClassLoader serviceClassLoader = serviceClass.getClassLoader();
    final Class<?> interfaceClass = Class.forName(name + "$Iface", false, serviceClassLoader);
    final Method[] methods = interfaceClass.getDeclaredMethods();
    final Map<String, String> docStrings = ThriftDocString.getAllDocStrings(serviceClassLoader);

    final List<FunctionInfo> functions = new ArrayList<>(methods.length);
    final Set<ClassInfo> classes = new LinkedHashSet<>();
    for (Method method : methods) {
        final FunctionInfo function = FunctionInfo.of(method, sampleRequests, name, docStrings);
        functions.add(function);/*from ww  w . j  a  va2s. com*/

        addClassIfPossible(classes, function.returnType());
        function.parameters().stream().forEach(p -> addClassIfPossible(classes, p.type()));
        function.exceptions().stream().forEach(e -> {
            e.fields().stream().forEach(f -> addClassIfPossible(classes, f.type()));
            addClassIfPossible(classes, e);
        });
    }

    return new ServiceInfo(name, functions, classes, endpoints, docStrings.get(name));
}

From source file:com.attilax.zip.FileUtil.java

@SuppressWarnings("unchecked")
public static final Map<String, String> getPropertiesMap(Class clazz, String fileName) throws Exception {
    Properties properties = new Properties();
    InputStream inputStream = clazz.getResourceAsStream(fileName);
    if (inputStream == null)
        inputStream = clazz.getClassLoader().getResourceAsStream(fileName);
    properties.load(inputStream);/*from ww w.j  a  v a  2  s .c  o m*/
    Map<String, String> map = new HashMap<String, String>();
    Set<Object> keySet = properties.keySet();
    for (Object key : keySet) {
        map.put((String) key, properties.getProperty((String) key));
    }
    return map;
}

From source file:SwingResourceManager.java

/**
 * Returns an image stored in the file at the specified path relative to the specified class
 * @param clazz Class The class relative to which to find the image
 * @param path String The path to the image file
 * @return Image The image stored in the file at the specified path
 *//*from   w  w w.ja v a 2s.  c o m*/
public static Image getImage(Class<?> clazz, String path) {
    String key = clazz.getName() + '|' + path;
    Image image = m_ClassImageMap.get(key);
    if (image == null) {
        if ((path.length() > 0) && (path.charAt(0) == '/')) {
            String newPath = path.substring(1, path.length());
            image = getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath)));
        } else {
            image = getImage(clazz.getResourceAsStream(path));
        }
        m_ClassImageMap.put(key, image);
    }
    return image;
}

From source file:org.deeplearning4j.hadoop.util.HdfsUtils.java

public static String findJar(Class<?> my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {/*  w  ww  . j  av a 2s.  c om*/
        for (Enumeration<?> itr = loader.getResources(class_file); 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:Util.java

/**
 * Append Class Info//from   ww w  . j  a  v  a  2 s . c  om
 * 
 * @param buffer
 *          the buffer to append to
 * @param clazz
 *          the class to describe
 */
protected static void appendClassInfo(StringBuffer buffer, Class clazz) {
    buffer.append("[class=").append(clazz.getName());
    buffer.append(" classloader=").append(clazz.getClassLoader());
    buffer.append(" interfaces={");
    Class[] interfaces = clazz.getInterfaces();
    for (int i = 0; i < interfaces.length; ++i) {
        if (i > 0)
            buffer.append(", ");
        buffer.append("interface=").append(interfaces[i].getName());
        buffer.append(" classloader=").append(interfaces[i].getClassLoader());
    }
    buffer.append("}]");
}

From source file:com.openteach.diamond.container.Container.java

/**
 * ??/*from   ww w .  j  a  va  2  s  . c o m*/
 */
static ClassLoader getBundleClassLoader(String bundleName, String className) {
    Bundle[] bundles = context.getBundles();
    for (int i = 0; i < bundles.length; i++) {
        String symbolicName = bundles[i].getSymbolicName().toLowerCase();
        if (symbolicName.equals(bundleName)) {
            try {
                Class<?> c = bundles[i].loadClass(className);
                if (c != null) {
                    return c.getClassLoader();
                }
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    }
    return null;
}

From source file:api_proto3.TestElf.java

public static void setSlf4jLogLevel(Class<?> clazz, Level logLevel) {
    try {/* w  w w  .j a v  a  2 s  .  co m*/
        //Log4jLogger log4Jlogger = (Log4jLogger) LoggerFactory.getLogger(clazz);
        Log4JLogger log4Jlogger = (Log4JLogger) LoggerFactory.getLogger(clazz);

        //Field field = clazz.getClassLoader().loadClass("org.apache.logging.slf4j.Log4jLogger").getDeclaredField("logger");
        Field field = clazz.getClassLoader().loadClass("org.apache.commons.logging.impl.Log4JLogger")
                .getDeclaredField("logger");
        field.setAccessible(true);

        Logger logger = (Logger) field.get(log4Jlogger);
        logger.setLevel(logLevel);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}