Gradle Kotlin DSL中yGuard配置异常:需保留类仍被混淆求助
yGuard Gradle Kotlin DSL配置失效排查与解决
问题背景
构建含第三方依赖的库,需求为仅混淆私有代码,保留其余所有内容,但配置后patternset指定的第三方类(如kotlin.*)仍被混淆,仅my.pack.MyClass的public方法按预期保留。
现有配置
"yguard" { "inoutpair"("in" to unobfJar, "out" to archivePath) // 防止yGuard移除.class文件中的Deprecated属性 "attribute"("name" to "Deprecated") "externalclasses" { "pathelement"("path" to sourceSets["main"].compileClasspath.asPath) } "rename"("logfile" to "${projectDir}/build/${rootProject.name}_renamelog.xml") { "keep" { "class"( "name" to "my.pack.MyClass", "methods" to "public", ) "class" { "classes" to "private" "methods" to "private" "fields" to "private" "patternset" { "include"("name" to "kotlin.*") "include"("name" to "kotlin.**") "include"("name" to "kotlin.**$*") "include"("name" to "kotlin.**$*$*") "include"("name" to "kotlin.**.*") // 此处还有更多com.fasterxml.*等包的include规则 } } } } }
混淆日志异常示例
</expose> <map> <method class="kotlin.random.jdk8.PlatformThreadLocalRandom" name="double nextDouble(double)" map="A"/> ... <field class="kotlin.enums.EnumEntriesList" name="entries" map="d"/> ...更多其他包下的类混淆记录
问题分析与解决方案
1. patternset指定类被混淆的原因
你的keep块中第二个class节点配置逻辑错误:
classes" to "private"、methods" to "private"、fields" to "private"的作用是仅保留匹配类中的私有成员,而非保留整个类不被混淆,这和你「保留第三方类」的需求完全相反。- 冗余的
include规则(如kotlin.**$*)会干扰匹配逻辑,kotlin.**已经可以匹配kotlin包下所有类(包括子包、内部类)。
修正后的keep块配置
"keep" { // 保留自定义类的public方法 "class"( "name" to "my.pack.MyClass", "methods" to "public", ) // 保留指定第三方包下的所有类及成员 "class" { "patternset" { "include"("name" to "kotlin.**") "include"("name" to "com.fasterxml.**") // 其他需要保留的第三方包 } // 明确保留类的所有方法和字段(可选,默认yGuard会保留必要成员,但显式配置更稳妥) "methods" to "*" "fields" to "*" } }
2. externalclasses属性的作用与正确用法
externalclasses用于告知yGuard:这些路径下的类是外部依赖,无需混淆、无需打包到输出jar,yGuard会在混淆时忽略这些类,避免因引用外部类导致的混淆错误。
常见配置误区
你当前使用sourceSets["main"].compileClasspath.asPath仅包含编译期依赖,而yGuard需要的是运行时依赖的完整classpath,编译依赖可能包含仅编译期使用的库(如注解处理器),会导致yGuard无法正确识别实际运行依赖的类。
正确配置示例
"externalclasses" { "pathelement"("path" to configurations.runtimeClasspath.asPath) }
配置后,yGuard会自动排除外部依赖类的混淆操作,同时确保你的代码对外部类的引用不会因为混淆而断裂。
内容的提问来源于stack exchange,提问作者Alex1024
相关产品推荐
相关产品推荐

