Java Resource Find findResource(Class clazz)

Here you can find the source of findResource(Class clazz)

Description

find Resource

License

Open Source License

Declaration

public static URL findResource(Class<?> clazz) 

Method Source Code

//package com.java2s;
/*//from   w  w  w  .  j ava 2s .c  o  m
  GRANITE DATA SERVICES
  Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
    
  This file is part of Granite Data Services.
    
  Granite Data Services is free software; you can redistribute it and/or modify
  it under the terms of the GNU Library General Public License as published by
  the Free Software Foundation; either version 2 of the License, or (at your
  option) any later version.
    
  Granite Data Services is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
  for more details.
    
  You should have received a copy of the GNU Library General Public License
  along with this library; if not, see <http://www.gnu.org/licenses/>.
*/

import java.lang.reflect.Type;

import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static URL findResource(Class<?> clazz) {
        if (clazz.isArray())
            clazz = clazz.getComponentType();
        if (clazz.isPrimitive())
            return null;
        URL url = getClassLoader(clazz).getResource(toResourceName(clazz));
        String path = url.toString();
        if (path.indexOf(' ') != -1) {
            try {
                url = new URL(path.replace(" ", "%20"));
            } catch (MalformedURLException e) {
                // should never happen...
            }
        }
        return url;
    }

    public static boolean isPrimitive(Type type) {
        return type instanceof Class<?> && ((Class<?>) type).isPrimitive();
    }

    public static ClassLoader getClassLoader(Class<?> clazz) {
        return (clazz.getClassLoader() != null ? clazz.getClassLoader() : ClassLoader.getSystemClassLoader());
    }

    public static String toResourceName(Class<?> clazz) {
        return clazz.getName().replace('.', '/').concat(".class");
    }
}

Related

  1. findResource(Class clazz)
  2. findResource(String name)
  3. findResource(String resource, ClassLoader classLoader)
  4. findResourceBase(String baseResource, ClassLoader loader)
  5. findResourceBases(String baseResource, ClassLoader loader)