beta.blog

Archive for March, 2025

Gradle: Print Bytecode Version of all class files

by on Mar.01, 2025, under News

The following code snippet contains logic to print the Java Bytecode Version for all class files.

task analyzeBytecode {
    doLast {
        // Iterate over all subprojects
        subprojects.each { subproject ->
            def runtimeClasspath = subproject.configurations.findByName('runtimeClasspath')
            if (runtimeClasspath) {
                runtimeClasspath.each { file ->
                    println "Analyzing: ${file.name} in ${subproject.name}"
                    try {
                        def jarFile = new java.util.jar.JarFile(file)
                        jarFile.entries().asIterator().each { entry ->
                            if (entry.name.endsWith(".class")) {
                                def inputStream = jarFile.getInputStream(entry)
                                def magicAndVersion = new byte[8]
                                inputStream.read(magicAndVersion)
                                def majorVersion = magicAndVersion[7] & 0xFF
                                println "Class: ${entry.name}, Bytecode version: ${majorVersion}"
                            }
                        }
                    } catch (Exception e) {
                        println "Failed to analyze ${file.name}: ${e.message}"
                    }
                }
            } else {
                println "No runtimeClasspath found for ${subproject.name}"
            }
        }
    }
}
Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!