できない.dev

Gradle「Could not find method compile() for arguments」の原因と直し方

Could not find method compile() は、compile を implementation に書き換えれば直る。
compile と runtime の設定は Gradle 7 で削除されたので、古い build.gradle をそのまま使うと出る。

公開:

要約

古い手順書のとおりに dependencies を書くと、ビルドが設定の読み込みで止まる。
Gradle 9.8.1 で compile 'org.apache.commons:commons-lang3:3.17.0' と書いた build.gradle を実行すると、次のように出た。

FAILURE: Build failed with an exception.
 
* Where:
Build file '/home/user/app/build.gradle' line: 8
 
* What went wrong:
A problem occurred evaluating root project 'app'.
> Could not find method compile() for arguments [org.apache.commons:commons-lang3:3.17.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Could not find method compile() for arguments は、compile という依存の設定(configuration)が存在しないという意味だ。
Groovy DSL では dependencies の中の compile '…' がメソッド呼び出しとして解釈されるので、設定が無いと「メソッドが見つからない」という形のエラーになる。line: の行番号が、書き換える行を指している。

Upgrading from Gradle 6.x to 7.0(新しいタブで開く) にあるとおり、compile と runtime の設定は Gradle 7 で削除された。
代わりの implementation と api は Gradle 3.4 からある。

解決策

1. 新しい設定名に書き換える

Gradle の移行ガイドにある対応表どおりに書き換える。

| 削除された設定 | 書き換え先 | |---|---| | compile | implementation(ライブラリの API に出るものは api) | | runtime | runtimeOnly | | testCompile | testImplementation | | testRuntime | testRuntimeOnly |

plugins {
    id 'java'
}
 
repositories {
    mavenCentral()
}
 
dependencies {
    implementation 'org.apache.commons:commons-lang3:3.17.0'
    testImplementation 'junit:junit:4.13.2'
}

Gradle 9.8.1 でこの build.gradle に書き換えると、gradle build が通り、compileClasspath に commons-lang3:3.17.0 が入った。

2. プラグインを適用する

implementation が見つからないなら、plugins ブロックに java を足す。
ほかのプロジェクトから使われるライブラリで、依存を利用側のコンパイルにも見せたいときは java-library を適用して api を使う(The Java Library Plugin(新しいタブで開く))。

plugins {
    id 'java-library'
}
 
dependencies {
    api 'org.apache.commons:commons-lang3:3.17.0'
}

3. Kotlin DSL も同じ名前に直す

build.gradle.kts でも、設定の名前は同じだ。

dependencies {
    implementation("org.apache.commons:commons-lang3:3.17.0")
    testImplementation("junit:junit:4.13.2")
}

よくある原因

  1. Gradle 6 以前の書き方が残っている。compile・testCompile・runtime・testRuntime は、どれも Gradle 7 で消えた。
    Gradle 9.8.1 では runtime も Could not find method runtime() になった。
  2. java プラグインを適用していない。implementation や testImplementation は、java などのプラグインが追加する設定である。
    プラグインの無い build.gradle に implementation を書くと、Could not find method implementation() になった。
  3. api を java プラグインで使っている。api は java-library プラグインにしか無い。java プラグインのまま api を書くと Could not find method api() になり、java-library に変えると通った。
  4. Kotlin DSL で古い書き方をしている。build.gradle.kts では同じ原因が、スクリプトのコンパイルエラー Unresolved reference 'compile' として出る。