微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Proguard 缩小 Gradle ShadowJar 输出以创建最小化的胖 Java jar?

如何解决如何使用 Proguard 缩小 Gradle ShadowJar 输出以创建最小化的胖 Java jar?

我想缩小一个使用 Gradle shadow plugin 创建的胖罐子。这样做的原因是我需要在完成的 jar 中的特定包中保留一些类,因为它们用于动态类生成(例如 Class.forName(...)),并且该插件不允许我指定要保留的包在 shadow jar 任务中调用 minimize() 时)。因此,我使用 Proguard Gradle plugin

buildscript {
    dependencies {
        classpath 'net.sf.proguard:proguard-gradle:6.2.2'
        classpath 'net.sf.proguard:proguard-base:6.2.2'
    }
}

plugins {
    id 'java-library'
    id 'application'
    id 'com.github.johnrengelman.shadow' version '5.2.0'
}

sourceCompatibility = 1.11

shadowJar {
    zip64 true
}

application {
    mainClassName = 'com.example.MyApp'
}

task proguard(type: proguard.gradle.ProGuardTask) {
    dependsOn shadowJar
    injars shadowJar

    outjars "${buildDir}/libs/${project.name}-${project.version}-proguard.jar"

    dontobfuscate
    dontoptimize
    keep 'class com.example.packagetokeep.*'

    // next block taken verbatim from Proguard's documentation examples:

    // Automatically handle the Java version of this build.
    if (System.getProperty('java.version').startsWith('1.')) {
        // Before Java 9,the runtime classes were packaged in a single jar file.
        libraryjars "${System.getProperty('java.home')}/lib/rt.jar"
    } else {
        // As of Java 9,the runtime classes are packaged in modular jmod files.
        libraryjars "${System.getProperty('java.home')}/jmods/java.base.jmod",jarfilter: '!**.jar',filter: '!module-info.class'
    }
}

所以,我想要做的是创建一个包含所有依赖项的胖 jar,然后传递给 Proguard 以最小化。目前,我不想优化或混淆。

当我尝试运行任务时,对于 can't find referenced classjavax.xml.stream.events.Attributejava.sql.Timestamp 等类,我收到了许多 java.util.logging.Level 形式的错误。我认为这是因为 Proguard 没有选择 Java 运行时库。这是错误摘要

Warning: there were 75920 unresolved references to classes or interfaces.
         You may need to add missing library jars or update their versions.
         If your code works fine without the missing classes,you can suppress
         the warnings with '-dontwarn' options.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedclass)
Warning: there were 670 unresolved references to program class members.
         Your input classes appear to be inconsistent.
         You may need to recompile the code.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedprogramclassmember)
Warning: there were 4 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)

如何让 Proguard 与 Gradle 和 Java 11 配合使用?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。