自定义Gradle插件时,需要混淆jar文件,想当然的就去实例化 ProGuardTask
class MyCustomPlugin extends Plugin<Project> {
void apply(Project target) {
// ...
// 混淆
ProGuardTask proGuardJar= new ProGuardTask();
proGuardJar.dependsOn(archiveClasses);
proGuardJar.injars("build/libs/classes.jar");
proGuardJar.outjars("build/release.jar");
proGuardJar.configuration("proguard-rules.pro");
// ...
}
}
结果报错:
org.gradle.api.tasks.TaskInstantiationException: Task of type 'proguard.gradle.ProGuardTask' has been instantiated directly which is not supported. Tasks can only be created using the Gradle API or DSL.
正确的做法应该是调用 target.getTasks().create()
创建一个任务对象
class MyCustomPlugin extends Plugin<Project> {
void apply(Project target) {
// ...
// 混淆
ProGuardTask proGuardJar = target.getTasks().create("proGuardJar", ProGuardTask.class);
proGuardJar.dependsOn(archiveClasses);
proGuardJar.injars("build/libs/classes.jar");
proGuardJar.outjars("build/release.jar");
proGuardJar.configuration("proguard-rules.pro");
// ...
}
}
使用ProGuardTask
需要在build.gradle
中添加依赖
dependencies {
implementation gradleApi()
implementation group: 'net.sf.proguard', name: 'proguard-gradle', version: '6.0.3'
}