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

使用JavaParser生成继承代码时如何避免ClassOrInterfaceType弃用警告

解决JavaParser中ClassOrInterfaceType构造方法弃用的问题

在使用JavaParser生成继承关系时,你遇到的new ClassOrInterfaceType("CustomEndpointResource")构造方法弃用警告,可以通过以下两种官方推荐的方式解决:

方法一:使用ClassOrInterfaceType.name()静态方法(推荐)

该方法是JavaParser专门提供的类型安全API,用于创建简单的类/接口类型节点,代码更简洁直观:

// 替换原有的extendsList相关代码,直接添加父类
restEndpointClass.addExtendedType(ClassOrInterfaceType.name("CustomEndpointResource"));

如果需要批量设置父类(Java仅支持单继承,此处为通用场景示例),也可配合NodeList使用:

NodeList<ClassOrInterfaceType> extendsList = new NodeList<>();
extendsList.add(ClassOrInterfaceType.name("CustomEndpointResource"));
restEndpointClass.setExtendedTypes(extendsList);

方法二:使用ClassOrInterfaceType.parse()静态方法

该方法支持解析复杂类型(如带泛型的类名),对于简单类名同样适用:

restEndpointClass.addExtendedType(ClassOrInterfaceType.parse("CustomEndpointResource"));

修改后的完整代码

替换原代码中设置继承的部分后,完整代码如下:

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.expr.StringLiteralExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;

public class ProductCreate2 {

    public static void main(String[] args) {
        CompilationUnit compilationUnit = new CompilationUnit();
        compilationUnit.setPackageDeclaration("org.meveo.mymodule.resource");
        compilationUnit.addImport("java.util", false, true);

        ClassOrInterfaceDeclaration restEndpointClass = compilationUnit.addClass("ProductCreate",Modifier.Keyword.PUBLIC);
        restEndpointClass.addSingleMemberAnnotation("Path",new StringLiteralExpr("myproduct"));
        restEndpointClass.addMarkerAnnotation("RequestScoped");

        var injectedfield=restEndpointClass.addField("CreateMyProduct", "CreateMyProduct", Modifier.Keyword.PRIVATE);
        injectedfield.addMarkerAnnotation("Inject");

        // 替换弃用的构造方法调用
        restEndpointClass.addExtendedType(ClassOrInterfaceType.name("CustomEndpointResource"));

        System.out.println(compilationUnit);
    }
}

说明

单参数的ClassOrInterfaceType构造方法被弃用,是因为JavaParser团队希望开发者使用更符合API设计理念的静态工厂方法,这些方法能更好地处理类型解析、命名空间等细节,同时提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:39:41