能否在AsciiDoctor文档中直接引用Java常量值?
Asciidoctor 引用 Java 常量的实现方案
有3种常用方案可以实现无需手动同步常量值的需求,无需每次修改Java代码后手动更新文档:
方案1:构建阶段提取常量生成Asciidoctor属性文件(最通用,无自定义开发)
这是企业级文档项目最常用的方案,通过构建工具(Gradle/Maven)在编译阶段提取Java常量,生成Asciidoctor属性定义文件,主文档直接引用属性即可。
操作步骤:
- 新增构建任务,从Java代码中提取常量,生成属性文件。以Gradle为例,任务示例如下:
task generateAsciidocAttributes { // 输出属性文件路径 outputs.file "$buildDir/generated-sources/asciidoc-attributes.adoc" doLast { // 反射加载编译后的类,获取常量值 Class<?> myClazz = classLoader.loadClass("my.package.MyClass") String endpointValue = myClazz.getField("ENDPOINT").get(null) // 写入Asciidoctor属性格式 File attrFile = outputs.files.singleFile attrFile.text = """:myclass-endpoint: ${endpointValue} """ } } // 绑定asciidoctor任务依赖,保证构建文档前先生成属性 asciidoctor { dependsOn generateAsciidocAttributes }
- 在Asciidoc主文档头部引入生成的属性文件:
= 文档标题 include::$buildDir/generated-sources/asciidoc-attributes.adoc[] ==== My class ..... some descripton ..... It is exposed trough {myclass-endpoint}
- 每次构建文档时,属性会自动替换为当前Java代码里的常量值。
方案2:自定义AsciidoctorJ宏(实现你期望的直接引用语法)
如果想要实现类似{import my.package.MyClass#ENDPOINT}的直接引用效果,可以自定义AsciidoctorJ的内联宏,宏处理逻辑里通过反射/静态源码解析拿到常量值自动替换。
宏代码示例:
public class JavaConstantMacro extends InlineMacroProcessor { public JavaConstantMacro() { // 注册宏名为javaconst super("javaconst"); } @Override public Object process(ContentNode parent, String target, Map<String, Object> attributes) { // 拆分target为类全限定名和常量名 String[] parts = target.split("#"); try { Class<?> clazz = Class.forName(parts[0]); Object constantValue = clazz.getField(parts[1]).get(null); return createPhraseNode(parent, "quoted", constantValue.toString()); } catch (Exception e) { throw new RuntimeException("无法解析Java常量: " + target, e); } } }
注册宏后,在文档中可以直接使用如下语法引用:
==== My class ..... some descripton ..... It is exposed trough javaconst:my.package.MyClass#ENDPOINT[]
注意事项:
需要保证编译后的Java类在AsciidoctorJ运行的类路径下,才能正常加载类读取常量。如果不想依赖编译后的class,可以替换实现逻辑为JavaParser静态解析Java源文件提取常量值。
方案3:Maven资源过滤
如果使用Maven作为构建工具,也可以通过properties-maven-plugin先把Java常量导出到properties文件,再开启Asciidoc文件的资源过滤功能,自动替换占位符,原理和方案1一致。
内容的提问来源于stack exchange,提问作者Antoniossss
相关产品推荐
相关产品推荐

