如何使用 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 (将#修改为@)