Determine de qué archivo JAR es una clase


154

No estoy frente a un IDE en este momento, solo estoy mirando las especificaciones de la API.

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
    URL jar = src.getLocation();
}

Quiero determinar de qué archivo JAR es una clase. ¿Es esta la manera de hacerlo?


2
¿Hay alguna manera de hacer esto desde la consola? Algo así como java -findjar -cp /some/path/with/libs/*.jar my.java.Class-> my.jar.
kub1x

Respuestas:


191

Si. Funciona para todas las clases, excepto las clases cargadas por el cargador de clases bootstrap. La otra forma de determinar es:

Class klass = String.class;
URL location = klass.getResource('/' + klass.getName().replace('.', '/') + ".class");

Como notnoop señaló, el klass.getResource()método devuelve la ubicación del archivo de clase en sí. Por ejemplo:

jar:file:/jdk/jre/lib/rt.jar!/java/lang/String.class
file:/projects/classes/pkg/MyClass$1.class

El getProtectionDomain().getCodeSource().getLocation()método devuelve la ubicación del archivo jar o CLASSPATH

file:/Users/home/java/libs/ejb3-persistence-1.0.2.GA.jar
file:/projects/classes

Esto hace suposiciones sobre el mapeo del nombre de la clase al archivo de clase. ¿Funcionará correctamente para clases anónimas? Clases anidadas?
Thorbjørn Ravn Andersen

1
Esto apunta a la url de la clase, no al jar en sí. La URL debe analizarse para encontrar el archivo jar.
notnoop

@notnoop. He aclarado la respuesta.
Chandra Patni el

19
Es exactamente al revés, ya que está escrito en la respuesta, úselo getProtectionDomain().getCodeSource().getLocation()si desea obtener la ubicación del archivo jar
Peter

Gracias por esta respuesta, me inspiró a responder esta pregunta .
kriegaex

12

Echa un vistazo a la LiveInjector.findPathJar()de Lombok PatcherLiveInjector.java . Tenga en cuenta que se trata de casos especiales en los que el archivo no vive realmente en un jar, y es posible que desee cambiar eso.

/**
 * If the provided class has been loaded from a jar file that is on the local file system, will find the absolute path to that jar file.
 * 
 * @param context The jar file that contained the class file that represents this class will be found. Specify {@code null} to let {@code LiveInjector}
 *                find its own jar.
 * @throws IllegalStateException If the specified class was loaded from a directory or in some other way (such as via HTTP, from a database, or some
 *                               other custom classloading device).
 */
public static String findPathJar(Class<?> context) throws IllegalStateException {
    if (context == null) context = LiveInjector.class;
    String rawName = context.getName();
    String classFileName;
    /* rawName is something like package.name.ContainingClass$ClassName. We need to turn this into ContainingClass$ClassName.class. */ {
        int idx = rawName.lastIndexOf('.');
        classFileName = (idx == -1 ? rawName : rawName.substring(idx+1)) + ".class";
    }

    String uri = context.getResource(classFileName).toString();
    if (uri.startsWith("file:")) throw new IllegalStateException("This class has been loaded from a directory and not from a jar file.");
    if (!uri.startsWith("jar:file:")) {
        int idx = uri.indexOf(':');
        String protocol = idx == -1 ? "(unknown)" : uri.substring(0, idx);
        throw new IllegalStateException("This class has been loaded remotely via the " + protocol +
                " protocol. Only loading from a jar on the local file system is supported.");
    }

    int idx = uri.indexOf('!');
    //As far as I know, the if statement below can't ever trigger, so it's more of a sanity check thing.
    if (idx == -1) throw new IllegalStateException("You appear to have loaded this class from a local jar file, but I can't make sense of the URL!");

    try {
        String fileName = URLDecoder.decode(uri.substring("jar:file:".length(), idx), Charset.defaultCharset().name());
        return new File(fileName).getAbsolutePath();
    } catch (UnsupportedEncodingException e) {
        throw new InternalError("default charset doesn't exist. Your VM is borked.");
    }
}

2
Esto parece demasiado complicado para obtener algo muy simple. Simplemente me senté e intenté lo que encontré antes, y parece funcionar. Solo quería algo de validación.

Bien. Su código no maneja los archivos en las rutas de bootclass, y la solución de Chandra devuelve la url al archivo, no al archivo jar, por lo que deberá analizar la ruta para encontrar el archivo jar.
notnoop

2

Utilizar

String path = <Any of your class within the jar>.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 

Si esto contiene varias entradas, realice alguna operación de subcadena.


1
private String resourceLookup(String lookupResourceName) {



    try {

        if (lookupResourceName == null || lookupResourceName.length()==0) {
            return "";
        }
        // "/java/lang/String.class"

        // Check if entered data was in java class name format
        if (lookupResourceName.indexOf("/")==-1) {
            lookupResourceName = lookupResourceName.replaceAll("[.]", "/");
            lookupResourceName =  "/" + lookupResourceName + ".class";
        }

        URL url = this.getClass().getResource(lookupResourceName);
        if (url == null) {
            return("Unable to locate resource "+ lookupResourceName);

        }

        String resourceUrl = url.toExternalForm();

        Pattern pattern =
            Pattern.compile("(zip:|jar:file:/)(.*)!/(.*)", Pattern.CASE_INSENSITIVE);

        String jarFilename = null;
        String resourceFilename = null;
        Matcher m = pattern.matcher(resourceUrl);
        if (m.find()) {
            jarFilename = m.group(2);
            resourceFilename = m.group(3);
        } else {
            return "Unable to parse URL: "+ resourceUrl;

        }

        if (!jarFilename.startsWith("C:") ){
          jarFilename = "/"+jarFilename;  // make absolute path on Linux
        }

        File file = new File(jarFilename);
        Long jarSize=null;
        Date jarDate=null;
        Long resourceSize=null;
        Date resourceDate=null;
        if (file.exists() && file.isFile()) {

            jarSize = file.length();
            jarDate = new Date(file.lastModified());

            try {
                JarFile jarFile = new JarFile(file, false);
                ZipEntry entry = jarFile.getEntry(resourceFilename);
                resourceSize = entry.getSize();
                resourceDate = new Date(entry.getTime());
            } catch (Throwable e) {
                return ("Unable to open JAR" + jarFilename + "   "+resourceUrl +"\n"+e.getMessage());

            }

           return "\nresource: "+resourceFilename+"\njar: "+jarFilename + "  \nJarSize: " +jarSize+"  \nJarDate: " +jarDate.toString()+"  \nresourceSize: " +resourceSize+"  \nresourceDate: " +resourceDate.toString()+"\n";


        } else {
            return("Unable to load jar:" + jarFilename+ "  \nUrl: " +resourceUrl);

        }
    } catch (Exception e){
        return e.getMessage();
    }


}

El código anterior encontrará cualquier recurso en la ruta. Si en un frasco encontrará el frasco, imprima el tamaño y la fecha del frasco y el tamaño y la fecha del recurso dentro del frasco
Don
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.