You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建首个Gradle插件遇报错:无法找到CommonPluginClass实现类

Gradle插件实现类找不到问题排查与解决

问题描述

创建首个Gradle插件时遇到以下错误:

无法找到为插件'common-plugin'指定的实现类'CommonPluginClass',路径为jar:file
org.gradle.api.plugins.InvalidPluginException: 应用插件请求[id: 'common-plugin']时发生异常

在app模块通过plugins { id 'common-plugin' }引用插件时,抛出的具体异常:

  • 应用插件请求[id: 'common-plugin']时发生异常
  • 无法找到为插件'common-plugin'指定的实现类'CommonPluginClass.kt',路径为jar:file:/C:/Users/User/.gradle/caches/jars-9/******/convention.jar!/META-INF/gradle-plugins/common-plugin.properties

现有代码与配置

插件实现类(Kotlin)

class CommonPluginClass: Plugin<Project> {

    override fun apply(project: Project) {
        project.task("hello") {
            doLast {
                println ("Hello from the CommonPluginClass")
            }
        }
    }
}

convention模块build.gradle配置

plugins {
    id 'groovy-gradle-plugin'
}

gradlePlugin {
    plugins {
        commonPlugin {
            id = "common-plugin"
            implementationClass = "CommonPluginClass"
        }
    }
}

build-logic模块settings.gradle配置

dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "build-logic"
include(":convention")

错误原因分析

  1. 缺少完整类名声明:CommonPluginClass未指定包名,Gradle识别插件实现类需要全限定类名(包名+类名),默认包下的类在构建逻辑模块中无法被正确索引。
  2. 插件类型不匹配:使用Kotlin编写插件,但配置中引用groovy-gradle-plugin,该插件仅适配Groovy编写的Gradle插件,无法正确编译打包Kotlin插件类。

解决方案

步骤1:给插件类添加包声明

修改CommonPluginClass,添加自定义包名(示例为com.yourname.plugins,可根据实际需求修改):

package com.yourname.plugins

import org.gradle.api.Plugin
import org.gradle.api.Project

class CommonPluginClass: Plugin<Project> {

    override fun apply(project: Project) {
        project.task("hello") {
            doLast {
                println ("Hello from the CommonPluginClass")
            }
        }
    }
}

步骤2:更新convention模块的build.gradle配置

替换Groovy插件为Kotlin插件,并修改implementationClass为全限定类名:

plugins {
    id 'kotlin-gradle-plugin'
}

gradlePlugin {
    plugins {
        commonPlugin {
            id = "common-plugin"
            implementationClass = "com.yourname.plugins.CommonPluginClass"
        }
    }
}

步骤3:清理缓存并重新构建

执行命令清理缓存并重新构建build-logic模块:

./gradlew :build-logic:convention:clean :build-logic:convention:build

完成后重新同步app模块的Gradle配置。

验证

构建完成后,在app模块执行hello任务:

./gradlew :app:hello

若控制台输出Hello from the CommonPluginClass,说明插件已正常工作。

内容的提问来源于stack exchange,提问作者Thorny84

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 11:15:36