我想缩小使用 Gradle 阴影插件 创建的 fat jar。原因是我需要将一些类保留在已完成的 jar 中的特定包中,因为它们用于动态类生成(例如
Class.forName(...)
),并且该插件不允许我在调用时指定要保留的包minimize()
在影子罐子任务中)。因此,我使用 Proguard Gradle 插件。
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'
}
}
所以,我想做的是创建一个包含所有依赖项的 fat jar,然后传递给 Proguard 进行最小化。目前,我不想优化或混淆。
当我尝试运行该任务时,对于
can't find referenced class
、javax.xml.stream.events.Attribute
、java.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 配合使用?
关于缩小由
制成的脂肪罐,有两个部分com.github.johnrengelman.shadow
首先,shadow 有一个收缩任务,可以完成您可能尝试使用 progaurd 做的大部分事情:
tasks.withType<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar> {
minimize() {
exclude(dependency("ch.qos.logback:.*:.*")) //for example to keep this
}
}
如果您仍然想使用 progaurd,下一步是按照 @xeruf 在注释中建议的方式进行操作,并在
代码片段中使用
libraryjars
块而不是一个指令。