Java Class Loader getClassLocation(String className)

Here you can find the source of getClassLocation(String className)

Description

Returns a string representing the location of the class definition.

License

BSD License

Declaration

public static String getClassLocation(String className) throws ClassNotFoundException, IOException 

Method Source Code


//package com.java2s;
//License from project: BSD License 

import java.io.File;

import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;

public class Main {
    /**/*from  w  w w. j  a  v  a  2s .  co m*/
     * Returns a string representing the location of the class definition.
     *
     * throws ClassNotFoundException    If the class was not found in the current
     *                                  environment.
     * throws IOException               If the class is located in a jar and there
     *                                  was a problem opening a connection to 
     *                                  obtain the jar file location.
     */
    public static String getClassLocation(String className) throws ClassNotFoundException, IOException {
        // Try to create an instance of the Class
        Class myClass = Class.forName(className);

        // Get the intial location
        URL locationUrl = myClass.getProtectionDomain().getCodeSource().getLocation();
        String location = locationUrl.toString();

        // If the location is a jar file
        if (location.startsWith("jar")) {
            locationUrl = ((JarURLConnection) locationUrl.openConnection()).getJarFileURL();
            location = locationUrl.toString();
        }
        // If the location is a class file
        if (location.startsWith("file")) {
            File file = new File(locationUrl.getFile());
            location = file.getAbsolutePath();
        }

        // Return the location
        return location;
    }
}

Related

  1. getClassLoaderForDirectory(final File baseFolder)
  2. getClassloaderRootDir(Class forClass)
  3. getClassLoaders(ClassLoader baseClassLoader)
  4. getClassLoaderStack(ClassLoader cl)
  5. getClassLocation(Class clazz)
  6. getCustomClassloader(List entries)
  7. getFileFromClassLoader(String fileName)
  8. getFilesByPackgeName(String packageName, File _file, ClassLoader classLoader, List list)
  9. getJvmExtClassLoader()