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

使用WhatsApp4J库遇Java SE17预览特性报错求助

问题描述

开发定时WhatsApp消息发送器时,使用Auties00的WhatsApp4J库,添加连接代码后出现编译错误:

error: class file for .gradle/caches/modules-2/files-2.1/com.github.auties00/whatsappweb4j/3.3.1/d8c9b37af703062b20b137100d8dc11abe8a27f7/whatsappweb4j-3.3.1.jar(/it/auties/whatsapp/api/Whatsapp.class) uses preview features of Java SE 17.
(use --enable-preview to allow loading of class files which contain preview features)
1 error

当前环境:JDK 19、Gradle 7.6.1、Spring Boot 3.0.6,已升级JDK到19,手动添加--enable-preview参数无效。

build.gradle配置如下:

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.6'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'com.github.auties00:whatsappweb4j:3.3.1'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
    useJUnitPlatform()
}

主类代码:

package com.example.demo;

import it.auties.whatsapp.api.Whatsapp;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        Whatsapp.webBuilder()
                .newConnection()
                .build()
                .addLoggedInListener(() -> System.out.println("Connected"))
                .addDisconnectedListener(reason -> System.out.printf("Disconnected: %s%n", reason))
                .connect()
                .join();
    }
}
解决方案

1. 全局配置Gradle任务的预览特性参数

单独添加--enable-preview无效,是因为Gradle需要将该参数传递给编译、测试、运行所有相关任务。修改build.gradle,添加以下配置:

// 编译任务启用预览特性
tasks.withType(JavaCompile) {
    options.compilerArgs += '--enable-preview'
}

// 测试任务启用预览特性
tasks.withType(Test) {
    jvmArgs += '--enable-preview'
}

// 运行任务启用预览特性
tasks.withType(JavaExec) {
    jvmArgs += '--enable-preview'
}

同时确保编译目标版本与源码版本一致,避免版本冲突:

sourceCompatibility = '19'
targetCompatibility = '19'

2. 升级WhatsApp4J到最新稳定版

旧版本的WhatsApp4J依赖Java17的预览特性,后续版本可能已移除该依赖。修改dependencies中的版本号为最新稳定版:

implementation 'com.github.auties00:whatsappweb4j:最新版本号'

3. 验证JDK环境配置

确保项目使用的JDK确实为19:

  • 执行java -version和./gradlew -v确认终端环境的JDK版本
  • 在IDE中检查项目SDK配置,确保模块和项目级别的JDK均设置为19

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:57:52