Determina da quale file JAR proviene una classe


154

Al momento non sono di fronte a un IDE, sto solo guardando le specifiche dell'API.

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

Voglio determinare da quale file JAR proviene una classe. È questo il modo di farlo?


2
C'è un modo per farlo dalla console? Qualcosa del tipo java -findjar -cp /some/path/with/libs/*.jar my.java.Class-> my.jar.
kub1x,

Risposte:


191

Sì. Funziona per tutte le classi ad eccezione delle classi caricate dal classloader bootstrap. L'altro modo per determinare è:

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

Come sottolineato da notnoop, il klass.getResource()metodo restituisce la posizione del file di classe stesso. Per esempio:

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

Il getProtectionDomain().getCodeSource().getLocation()metodo restituisce la posizione del file jar o CLASSPATH

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

Questo rende le ipotesi sulla mappatura dal nome della classe al file di classe. Funzionerà correttamente per le classi anonime? Classi nidificate?
Thorbjørn Ravn Andersen,

1
Questo indica l'url della classe e non il vaso stesso. L'URL deve essere analizzato per trovare il file jar.
notnoop,

@notnoop. Ho chiarito la risposta.
Chandra Patni,

19
È esattamente il contrario, come è scritto nella risposta, usa getProtectionDomain().getCodeSource().getLocation()se vuoi ottenere la posizione del file jar
peter

Grazie per questa risposta, mi ha ispirato a rispondere a questa domanda .
Kriegaex,

12

Checkout la LiveInjector.findPathJar()da Lombok PatcherLiveInjector.java . Si noti che si tratta di casi speciali in cui il file in realtà non vive in un barattolo e potrebbe essere necessario modificarlo.

/**
 * 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
Questo sembra eccessivamente complicato per ottenere qualcosa di molto semplice. Mi sono appena seduto e ho provato quello che ho trovato prima, e sembra funzionare. Volevo solo un po 'di convalida.

Bene. Il tuo codice non gestisce i file nei percorsi di bootclass e la soluzione di Chandra restituisce l'URL al file e non al file jar, quindi dovrai trovare il percorso per trovare il file jar.
notnoop,

2

Uso

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

Se questo contiene più voci, eseguire alcune operazioni di sottostringa.


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();
    }


}

Il codice sopra troverà qualsiasi risorsa sul percorso. Se in un vaso troverai il vaso, stampa le dimensioni e la data del vaso e le dimensioni e la data della risorsa all'interno del vaso
Don
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.