Encontrar una clase en algún lugar dentro de docenas de archivos JAR?


¿Cómo encontrarías un nombre de clase particular dentro de muchos archivos jar?

(Buscando el nombre real de la clase, no las clases que la hacen referencia.)

Author: Vadim Kotov, 2009-08-27

30 answers

Eclipse puede hacerlo, simplemente cree un proyecto (temporal) y ponga sus bibliotecas en el classpath de proyectos. Entonces usted puede encontrar fácilmente las clases.

Otra herramienta que me viene a la mente es Java Decompiler. Puede abrir muchos frascos a la vez y ayuda a encontrar clases también.

 52
Author: Andreas_D,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-27 18:32:00

Unix

Utilice el jar (o unzip -v), grep, y find órdenes.

Por ejemplo, lo siguiente listará todos los archivos de clase que coincidan con un nombre dado:

for i in *.jar; do jar -tvf "$i" | grep -Hsi ClassName && echo "$i"; done

Si conoce toda la lista de archivos Java que desea buscar, podría colocarlos todos en el mismo directorio utilizando enlaces (simbólicos).

O use find (sensible a mayúsculas y minúsculas) para encontrar el archivo JAR que contiene un nombre de clase dado:

find path/to/libs -name '*.jar' -exec grep -Hls ClassName {} \;

Por ejemplo, para encontrar el nombre del archivo que contengan IdentityHashingStrategy:

$ find . -name "*.jar" -exec grep -Hsli IdentityHashingStrategy {} \;
./trove-3.0.3.jar

Si el FRASCO podría estar en cualquier lugar en el sistema y el locate el comando está disponible:

for i in $(locate "*.jar");
  do echo $i; jar -tvf $i | grep -Hsi ClassName;
done

Windows

Abra un símbolo del sistema , cambie al directorio (o directorio antepasado) que contiene los archivos JAR, luego:

for /R %G in (*.jar) do @jar -tvf "%G" | find "ClassName" > NUL && echo %G

Así es como funciona:

  1. for /R %G in (*.jar) do - loop sobre todos los archivos JAR, atravesando recursivamente directorios; almacena el nombre del archivo en % G.
  2. @jar -tvf "%G" | - ejecutar el Java Comando Archive para listar todos los nombres de archivo dentro del archivo dado, y escribir los resultados en la salida estándar; el símbolo @ suprime la impresión de la invocación del comando.
  3. find "ClassName" > NUL - buscar entrada estándar, canalizada desde la salida del comando jar, para el nombre de clase dado; esto establecerá ERRORLEVEL a 1 si hay una coincidencia (de lo contrario 0).
  4. && echo %G - iff ERRORLEVEL es distinto de cero, escriba el nombre del archivo de archivo Java en la salida estándar (la consola).

Web

Uso un motor de búsqueda que escanea archivos JAR.

 337
Author: Dave Jarvis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-24 21:44:35

Hace algún tiempo, escribí un programa justo para eso: https://github.com/javalite/jar-explorer

 53
Author: ipolevoy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 05:27:48
grep -l "classname" *.jar

Te da el nombre del frasco

find . -name "*.jar" -exec jar -t -f {} \; | grep  "classname"

Te da el paquete de la clase

 21
Author: user311174,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-22 14:43:24
#!/bin/bash

pattern=$1
shift

for jar in $(find $* -type f -name "*.jar")
do
  match=`jar -tvf $jar | grep $pattern`
  if [ ! -z "$match" ]
  then
    echo "Found in: $jar"
    echo "$match"
  fi
done
 11
Author: Pascal Lambert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-11 16:31:34

No sabía de una utilidad para hacerlo cuando me encontré con este problema, así que escribí lo siguiente:

public class Main {

    /**
     * 
     */
    private static String CLASS_FILE_TO_FIND =
            "class.to.find.Here";
    private static List<String> foundIn = new LinkedList<String>();

    /**
     * @param args the first argument is the path of the file to search in. The second may be the
     *        class file to find.
     */
    public static void main(String[] args) {
        if (!CLASS_FILE_TO_FIND.endsWith(".class")) {
            CLASS_FILE_TO_FIND = CLASS_FILE_TO_FIND.replace('.', '/') + ".class";
        }
        File start = new File(args[0]);
        if (args.length > 1) {
            CLASS_FILE_TO_FIND = args[1];
        }
        search(start);
        System.out.println("------RESULTS------");
        for (String s : foundIn) {
            System.out.println(s);
        }
    }

    private static void search(File start) {
        try {
            final FileFilter filter = new FileFilter() {

                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".jar") || pathname.isDirectory();
                }
            };
            for (File f : start.listFiles(filter)) {
                if (f.isDirectory()) {
                    search(f);
                } else {
                    searchJar(f);
                }
            }
        } catch (Exception e) {
            System.err.println("Error at: " + start.getPath() + " " + e.getMessage());
        }
    }

    private static void searchJar(File f) {
        try {
            System.out.println("Searching: " + f.getPath());
            JarFile jar = new JarFile(f);
            ZipEntry e = jar.getEntry(CLASS_FILE_TO_FIND);
            if (e == null) {
                e = jar.getJarEntry(CLASS_FILE_TO_FIND);
                if (e != null) {
                    foundIn.add(f.getPath());
                }
            } else {
                foundIn.add(f.getPath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 7
Author: ILMTitan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-27 18:34:35

Para localizar jars que coincidan con una cadena dada:

find . -name \*.jar -exec grep -l YOUR_CLASSNAME {} \;

 6
Author: George Armhold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-03 01:46:54

También hay dos utilidades diferentes llamadas "JarScan" que hacen exactamente lo que está pidiendo: JarScan (inetfeedback.com) y JarScan (java.net)

 5
Author: salzo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-08 02:57:53

El script de User1207523 funciona bien para mí. Aquí hay una variante que busca archivos jar de forma recursiva usando find en lugar de una simple expansión;

#!/bin/bash
for i in `find . -name '*.jar'`; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done
 3
Author: Kurtcebe Eroglu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-19 11:22:22

Siempre he utilizado esto en Windows y su funcionó excepcionalmente bien.

findstr /s /m /c:"package/classname" *.jar, where

Findstr.exe viene de serie con Windows y los parámetros:

  • / s = recursivamente
  • / m = imprime solo el nombre del archivo si hay una coincidencia
  • / c = cadena literal (en este caso su nombre de paquete + nombres de clase separados por '/')

Espero que esto ayude a alguien.

 3
Author: Ramesh Rooplahl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-21 14:42:28

Una solución bash script usando unzip (zipinfo). Probado en Ubuntu 12.

#!/bin/bash

# ./jarwalker.sh "/a/Starting/Path" "aClassName"

IFS=$'\n'
jars=( $( find -P "$1" -type f -name "*.jar" ) )

for jar in ${jars[*]}
    do
        classes=( $( zipinfo -1 ${jar} | awk -F '/' '{print $NF}' | grep .class | awk -F '.' '{print $1}' ) )
        if [ ${#classes[*]} -ge 0 ]; then
            for class in ${classes[*]}
                do
                    if [ ${class} == "$2" ]; then
                        echo "Found in ${jar}"
                    fi
                done
        fi
    done
 2
Author: Filippo Lauria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-21 09:54:12

Encontré este nuevo camino

bash $ ls -1  | xargs -i -t jar -tvf '{}'| grep Abstract
jar -tvf activation-1.1.jar
jar -tvf antisamy-1.4.3.jar
  2263 Thu Jan 13 21:38:10 IST 2011 org/owasp/validator/html/scan/AbstractAntiSamyScanner.class
...

Así que esto enumera el jar y la clase si se encuentra, si lo desea puede dar ls -1 *.jar o entrada a xargs con find comando HTH Alguien.

 2
Author: Cleonjoys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-04 12:24:31

Compruebe JBoss Tattletale; aunque nunca lo he usado personalmente, esta parece ser la herramienta que necesita.

 1
Author: Wilfred Springer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-27 18:42:52

Simplemente use FindClassInJars util, es un programa de swing simple, pero útil. Puede consultar el código fuente o descargar el archivo jar en http://code.google.com/p/find-class-in-jars /

 1
Author: Liubing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-31 13:36:10

No estoy seguro de por qué los scripts aquí nunca han funcionado realmente para mí. Esto funciona:

#!/bin/bash
for i in *.jar; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done
 1
Author: Mikael Lindlöf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-04 12:38:30

Para buscar todos los archivos jar en un directorio dado para una clase en particular, puede hacer esto:

ls *.jar | xargs grep -F MyClass

O, aún más simple,

grep -F MyClass *.jar

La salida se ve así:

Binary file foo.jar matches

Es muy rápido porque la opción-F significa buscar cadena fija, por lo que no carga el motor de expresiones regulares para cada invocación grep. Si lo necesita, siempre puede omitir la opción-F y usar expresiones regulares.

 1
Author: Jeff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-19 18:00:59

Script para encontrar el archivo jar: find_jar.sh

IFS=$(echo -en "\n\b") # Set the field separator newline

for f in `find ${1} -iname *.jar`; do
  jar -tf ${f}| grep --color $2
  if [ $? == 0 ]; then
    echo -n "Match found: "
    echo -e "${f}\n"
  fi
done
unset IFS

Uso: ./find_jar.sh

Esto es similar a la mayoría de las respuestas dadas aquí. Pero solo muestra el nombre del archivo, si grep encuentra algo. Si desea suprimir la salida grep, puede redirigirla a /dev / null, pero prefiero ver la salida de grep también para poder usar nombres de clases parciales y averiguar la correcta de una lista de salida mostrada.

El el nombre de la clase puede ser un nombre de clase simple como " String "o un nombre completo como" java.lang.String "

 1
Author: Joydip Datta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 07:34:34

Para añadir otra herramienta... esta es una herramienta muy simple y útil para windows. Un simple archivo exe en el que haga clic, le dará un directorio para buscar, un nombre de clase y encontrará el archivo jar que contiene esa clase. Sí, es recursivo.

Http://sourceforge.net/projects/jarfinder /

 1
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-08 16:05:58

Puedes encontrar una clase en un directorio lleno de frascos con un poco de shell:

Buscando la clase "FooBar":

LIB_DIR=/some/dir/full/of/jarfiles
for jarfile in $(find $LIBDIR -name "*.jar"); do
   echo "--------$jarfile---------------"
   jar -tvf $jarfile | grep FooBar
done
 0
Author: Steve B.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-27 18:41:21

Una cosa para agregar a todo lo anterior: si no tiene el ejecutable jar disponible (viene con el JDK pero no con el JRE), puede usar unzip (o WinZip, o lo que sea) para lograr lo mismo.

 0
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-14 16:53:10

Desvergonzada auto promoción, pero usted puede probar una utilidad que escribí: http://sourceforge.net/projects/zfind

Es compatible con la mayoría de los archivos comprimidos (jar, zip, tar, tar.gz etc) y a diferencia de muchos otros buscadores jar/zip, admite archivos zip anidados (zip dentro de zip, jar dentro de jar, etc) hasta una profundidad ilimitada.

 0
Author: Dipankar Datta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-23 11:09:34

Un poco tarde para la fiesta, pero sin embargo...

He estado usando JarBrowser para encontrar en qué jar está presente una clase en particular. Tiene una interfaz gráfica de usuario fácil de usar que le permite navegar a través del contenido de todos los jars en la ruta seleccionada.

 0
Author: maccaroo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-15 00:41:20

El siguiente script te ayudará

for file in *.jar
do
  # do something on "$file"
  echo "$file"
  /usr/local/jdk/bin/jar -tvf "$file" | grep '$CLASSNAME'
done
 0
Author: Kartik Jajal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-08 10:05:53

Este funciona bien en MinGW ( entorno de Windows bash ) ~ gitbash

Ponga esta función en su .archivo bashrc en su directorio PERSONAL:

# this function helps you to find a jar file for the class
function find_jar_of_class() {
  OLD_IFS=$IFS
  IFS=$'\n'
  jars=( $( find -type f -name "*.jar" ) )
  for i in ${jars[*]} ; do 
    if [ ! -z "$(jar -tvf "$i" | grep -Hsi $1)" ] ; then
      echo "$i"
    fi
   done 
  IFS=$OLD_IFS
}
 0
Author: kisp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-08 09:48:39

Grepj es una utilidad de línea de comandos para buscar clases dentro de archivos jar. Soy el autor de la utilidad.

Puede ejecutar la utilidad como grepj package.Class my1.jar my2.war my3.ear

Se pueden proporcionar múltiples archivos jar, ear, war. Para un uso avanzado, use buscar para proporcionar una lista de frascos a buscar.

 0
Author: rrevo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-19 04:12:49

Compruebe este plugin para eclipse que puede hacer el trabajo que está buscando.

Https://marketplace.eclipse.org/content/jarchiveexplorer

 0
Author: kutty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-06 11:26:14

En un entorno Linux se puede hacer lo siguiente:

$ find <base_dir> -name *.jar -print0 | xargs -0 -l jar tf | grep <name>

Donde nombre es el nombre del archivo de clase que está buscando dentro de los jars distribuidos a través de la jerarquía de directorios arraigados en el base_dir.

 0
Author: Victor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-17 16:18:43

Puedes usar locate y grep:

locate jar | xargs grep 'my.class'

Asegúrese de ejecutar updatedb antes de usar locate.

 0
Author: mulugu mahesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-11 13:22:56

Use esto.. puedes encontrar cualquier archivo en classpath.. garantizar..

import java.net.URL;
import java.net.URLClassLoader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileFinder {

    public static void main(String[] args) throws Exception {

        String file = <your file name>;

        ClassLoader cl = ClassLoader.getSystemClassLoader();

        URL[] urls = ((URLClassLoader)cl).getURLs();

        for(URL url: urls){
            listFiles(file, url);
        }
    }

    private static void listFiles(String file, URL url) throws Exception{
        ZipInputStream zip = new ZipInputStream(url.openStream());
          while(true) {
            ZipEntry e = zip.getNextEntry();
            if (e == null)
              break;
            String name = e.getName();
            if (name.endsWith(file)) {
                System.out.println(url.toString() + " -> " + name);
            }
          }
    }

}
 0
Author: Apurva Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-28 17:13:10

En eclipse puedes usar el plugin antiguo pero aún utilizable jarsearch

 0
Author: keiki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-22 13:27:30