Java Class Path getClassFilePath(String package_name, String class_name)

Here you can find the source of getClassFilePath(String package_name, String class_name)

Description

get Class File Path

License

Open Source License

Declaration

public static String getClassFilePath(String package_name, String class_name) 

Method Source Code


//package com.java2s;
import java.io.File;

import java.net.*;

public class Main {
    public static String getClassFilePath(String package_name, String class_name) {

        String path = null;/*ww w  .  j av a2s .  c o  m*/
        try {
            Class c = Class.forName(package_name + "." + class_name);
            path = getClassFilePath(c);
        } catch (ClassNotFoundException e) {
            System.err.println("Could not locate class " + package_name + "." + class_name);
            path = null;
        }
        return path;
    }

    public static String getClassFilePath(Class c) {
        String out = null;

        // check for Windoze
        boolean windoze = (File.separatorChar == '\\');

        URL url = null;
        String fullyQualifiedName = c.getCanonicalName();
        String shortName = c.getSimpleName();
        String classRes = "/" + fullyQualifiedName.replace('.', '/') + ".class";
        url = c.getResource(classRes);

        // Make sure that the class was loaded from a class file
        // in a directory and not from a jar or from an applet
        if (url.getProtocol().equals("file")) {
            try {
                // Get the path
                // Sometimes JDKs produce null for path and you have to
                // get it from the scheme specific part (which in a 
                // file URI should just be the path)
                out = url.toURI().getPath();
                if (out == null) {
                    out = url.toURI().getSchemeSpecificPart();
                }

                // chop off the unneeded stuff
                out = out.substring(0, out.length() - (shortName + ".class").length());
                if (windoze && out.startsWith("/")) {
                    out = out.substring(1);
                }
            } catch (URISyntaxException e) {
                // Something has gone awry.  All valid URLs are URIs.
                throw new RuntimeException("Could not find " + fullyQualifiedName + " in classpath.");
            }

            out = out.replace('/', File.separatorChar);
        } else {
            // Not from a directory.  Return null.
            out = null;
        }
        return out;
    }
}

Related

  1. getClassBasePath(Class aClass)
  2. getClassFilePath(Class clazz)
  3. getClassFilePath(Class clazz)
  4. getClassFilePath(Class clazz)
  5. getClassFilePath(final Class cls)
  6. getClassNameByFile(String filePath, List className, boolean childPackage)
  7. getDirectoryPath(Class owner)
  8. getFile(Class base, String path)
  9. getFullPathOfClass(Class cls)