Java URL Resolve resolveRootUrl(Class knownClass)

Here you can find the source of resolveRootUrl(Class knownClass)

Description

Useful in cases where we need to deal with files/resources in the test compilation output dir of the project.

License

LGPL

Parameter

Parameter Description
knownClass Reference to a Class known to be in the compilation output dir.

Return

The root URL

Declaration

public static URL resolveRootUrl(Class knownClass) 

Method Source Code

//package com.java2s;
/*/*from w w w.  ja  v  a 2  s .c  om*/
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */

import java.net.MalformedURLException;

import java.net.URL;
import static java.io.File.separatorChar;

public class Main {
    /**
     * Useful in cases where we need to deal with files/resources in the test compilation output dir of the
     * project.  This gets a reference to the compilation output directory into which the given class was compiled.
     *
     * @param knownClass Reference to a Class known to be in the compilation output dir.
     *
     * @return The root URL
     */
    public static URL resolveRootUrl(Class knownClass) {
        final String knownClassFileName = '/' + knownClass.getName().replace('.', separatorChar) + ".class";
        final URL knownClassFileUrl = knownClass.getResource(knownClassFileName);
        final String knownClassFileUrlString = knownClassFileUrl.toExternalForm();

        // to start, strip off the class file name
        String rootUrlString = knownClassFileUrlString.substring(0,
                knownClassFileUrlString.lastIndexOf(separatorChar));

        // then strip off each package dir
        final String packageName = knownClass.getPackage().getName();
        for (String packageNamePart : packageName.split("\\.")) {
            rootUrlString = rootUrlString.substring(0, rootUrlString.lastIndexOf(separatorChar));
        }

        try {
            return new URL(rootUrlString);
        } catch (MalformedURLException e) {
            throw new RuntimeException("Could not convert class base url as string to URL ref", e);
        }
    }
}

Related

  1. resolvePlatformUrl(String urlspec)
  2. resolveRelativeURL(final URL primaryUrl, final String relativeLoc)
  3. resolveRelativeURL(String contextUri, String relativeUri)
  4. resolveResourceAsURL(Class clazz, String name)
  5. resolveResourceURL(Class base, String resource)
  6. resolveUrl(String url, Properties properties)
  7. resolveURL(String urlValue)
  8. resolveURL(URL base, String target)
  9. resolveURL(URL contextURL, String url)