Java Resource Get getResource(String resource, Class context)

Here you can find the source of getResource(String resource, Class context)

Description

Loads a URL resource from the classloader; If not found, the classloader of the context class specified will be used.

License

Apache License

Declaration

public static URL getResource(String resource, Class<?> context) 

Method Source Code


//package com.java2s;
//Licensed under the Apache License, Version 2.0 (the "License");

import java.net.URL;

public class Main {
    /**//from ww w  . java 2  s.  c o m
     * Loads a {@link URL} resource from the classloader;
     * If not found, the classloader of the {@code context} class specified will be used.
     */
    public static URL getResource(String resource, Class<?> context) {
        return getResource(resource, context, false);
    }

    /**
     * Loads a {@link URL} resource from the classloader;
     * If not found, the classloader of the {@code context} class specified will be used.
     * If the flag {@code checkParent} is true, the classloader's parent is included in 
     * the lookup.
     */
    public static URL getResource(String resource, Class<?> context, boolean checkParent) {
        URL url = Thread.currentThread().getContextClassLoader().getResource(resource);
        if (url != null)
            return url;

        if (context != null) {
            ClassLoader loader = context.getClassLoader();
            while (loader != null) {
                url = loader.getResource(resource);
                if (url != null)
                    return url;
                loader = checkParent ? loader.getParent() : null;
            }
        }

        return ClassLoader.getSystemResource(resource);
    }
}

Related

  1. getResource(String name)
  2. getResource(String name)
  3. getResource(String name, Class neighbor)
  4. getResource(String name, Class caller)
  5. getResource(String res)
  6. getResourceAsBytes(String resource)
  7. getResourceAsBytes(String resource)
  8. getResourceAsFile(Class clazz, String resource)
  9. getResourceAsFile(Class klass, String resource)