Herramienta para leer y mostrar Java.versiones de clase


Cualquiera de ustedes sabe de una herramienta que buscará .archivos de clase y luego mostrar sus versiones compiladas?

Sé que puedes mirarlos individualmente en un editor hexadecimal, pero tengo muchos archivos de clases que revisar (algo en mi aplicación gigante está compilando a Java6 por alguna razón).

 109
Author: aioobe, 2008-08-26

7 answers

Utilice la herramienta javap que viene con el JDK. La opción -verbose imprimirá el número de versión del archivo de clase.

> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
  SourceFile: "MyClass.java"
  minor version: 0
  major version: 46
...

Para mostrar solo la versión:

WINDOWS> javap -verbose MyClass | find "version"
LINUX  > javap -verbose MyClass | grep version
 135
Author: staffan,
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-03-08 15:22:24

Es bastante fácil leer la firma del archivo de clase y obtener estos valores sin una API de terceros. Todo lo que necesita hacer es leer los primeros 8 bytes.

ClassFile {
    u4 magic;
    u2 minor_version;
    u2 major_version;

Para el archivo de clase versión 51.0 (Java 7), los bytes de apertura son:

CA FE BA BE 00 00 00 33

...donde 0xCAFEBABE son los bytes mágicos, 0x0000 es la versión menor y 0x0033 es la versión mayor.

import java.io.*;

public class Demo {
  public static void main(String[] args) throws IOException {
    ClassLoader loader = Demo.class.getClassLoader();
    try (InputStream in = loader.getResourceAsStream("Demo.class");
        DataInputStream data = new DataInputStream(in)) {
      if (0xCAFEBABE != data.readInt()) {
        throw new IOException("invalid header");
      }
      int minor = data.readUnsignedShort();
      int major = data.readUnsignedShort();
      System.out.println(major + "." + minor);
    }
  }
}

Caminando directorios ( Archivo ) y archivos ( JarFile ) buscando archivos de clase es trivial.

Oracle Joe Darcy's blog enumera la class version to JDK version mappings hasta Java 7:

Target   Major.minor Hex
1.1      45.3        0x2D
1.2      46.0        0x2E
1.3      47.0        0x2F
1.4      48.0        0x30
5 (1.5)  49.0        0x31
6 (1.6)  50.0        0x32
7 (1.7)  51.0        0x33
8 (1.8)  52.0        0x34
9        53.0        0x35
 41
Author: McDowell,
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
2017-12-04 14:29:17

En Unix-like

file /path/to/Thing.class

También dará el tipo de archivo y la versión. Así es como se ve la salida:

Datos compilados de la clase Java, versión 49.0

 21
Author: phunehehe,
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-07-07 10:34:00

Si está en un sistema unix, simplemente podría hacer un

find /target-folder -name \*.class | xargs file | grep "version 50\.0"

(mi versión del archivo dice "compiled Java class data, version 50.0" para las clases java6).

 9
Author: WMR,
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
2008-08-26 12:32:05

Otra versión de java comprobar

od -t d -j 7 -N 1 ApplicationContextProvider.class | head -1 | awk '{print "Java", $2 - 44}'
 5
Author: igo,
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-08-08 10:30:37

En eclipse si no tiene fuentes adjuntas. Tenga en cuenta la primera línea después del botón adjuntar fuente.

// Compilado a partir de CDestinoLog.java (versión 1.5: 49.0, super bit )

introduzca la descripción de la imagen aquí

 4
Author: PbxMan,
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-01-29 08:49:08

Tal vez esto ayuda a alguien, también. Parece que hay una manera más fácil de obtener la versión de JAVA utilizada para compilar/construir .clase. Esta manera es útil para la auto-comprobación de la aplicación/clase en la versión de JAVA.

He pasado por la biblioteca JDK y he encontrado esta constante útil: com.sol.desplegar.config.Propiedades incorporadas.CURRENT_VERSION . No sé desde cuando está en JAVA JDK.

Probando esta pieza de código para varias constantes de versión obtengo el resultado abajo:

Src:

System.out.println("JAVA DEV       ver.: " + com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION);
System.out.println("JAVA RUN     v. X.Y: " + System.getProperty("java.specification.version") );
System.out.println("JAVA RUN v. W.X.Y.Z: " + com.sun.deploy.config.Config.getJavaVersion() ); //_javaVersionProperty
System.out.println("JAVA RUN  full ver.: " + System.getProperty("java.runtime.version")  + " (may return unknown)" );
System.out.println("JAVA RUN       type: " + com.sun.deploy.config.Config.getJavaRuntimeNameProperty() );

Salida:

JAVA DEV       ver.: 1.8.0_77
JAVA RUN     v. X.Y: 1.8
JAVA RUN v. W.X.Y.Z: 1.8.0_91
JAVA RUN  full ver.: 1.8.0_91-b14 (may return unknown)
JAVA RUN       type: Java(TM) SE Runtime Environment

En la clase bytecode realmente se almacena constante - ver rojo marcado parte de Principal.call - constante almacenada en .bytecode de clase

Constant está en la clase utilizada para comprobar si la versión de JAVA está desactualizada (ver Cómo Java comprueba que está desactualizada)...

 2
Author: Radoslav Kastiel,
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
2017-05-23 12:34:45