结合 @TypeChecked 实现编译期路径校验
解读
在国内一线互联网公司的 Groovy 面试中,这道题考察的是“在静态编译模式下,如何提前发现非法字符串路径,避免运行时 FileNotFoundException”。
面试官期望你不仅打开 @TypeChecked 开关,还要利用 AST 转换在编译期就把“路径是否存在”这一运行时语义固化成编译错误,从而把风险左移到 CI 阶段。
核心难点是:@TypeChecked 只能检查类型,不会主动检查字符串内容;必须自定义 AST 转换或借助宏/注解处理器,把“路径存在”这一业务语义注入到编译期。
知识点
- @TypeChecked 与 @CompileStatic 的区别:前者只做类型推断,不优化字节码;后者直接生成静态字节码。
- Groovy 编译期插件机制:实现 GroovyClassLoader 的 CompilationCustomizer,在 Semantic Analysis 阶段遍历 AST。
- AST 节点类型:MethodCallExpression、ConstantExpression、PropertyExpression。
- 注解驱动的局部类型检查:用 @PathExists 标记形参或字段,配合 ASTTransformation 在 CANONICALIZATION 阶段做路径校验。
- 国内工程化落地要点:
- 必须兼容 Windows/Linux 双环境路径分隔符;
- 报错信息要符合阿里/腾讯代码规约插件格式,方便 Sonar 采集;
- 单测用 Spock 编写,覆盖率红线 80% 以上。
答案
// 1. 定义注解
@Retention(RetentionPolicy.SOURCE)
@Target([ElementType.PARAMETER, ElementType.FIELD])
@interface PathExists {}
// 2. 实现 AST 转换
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
class PathExistsAST implements ASTTransformation {
void visit(ASTNode[] nodes, SourceUnit source) {
def methods = source.AST.classes*.methods.flatten()
methods.each { MethodNode mn ->
mn.parameters.each { Parameter p ->
if (p.getAnnotation(PathExists)) {
mn.code.each { stmt ->
stmt?.each { expr ->
if (expr instanceof ConstantExpression && expr.value instanceof String) {
def path = expr.value as String
if (!new File(path).exists()) {
source.addError(new SyntaxException(
"编译期路径校验失败:文件 $path 不存在", expr.line, expr.column))
}
}
}
}
}
}
}
}
}
// 3. 使用示例(在 @TypeChecked 模式下)
@TypeChecked
class ConfigService {
void load(@PathExists String cfgPath) {
// 如果传入字符串常量路径错误,编译直接失败
def json = new File(cfgPath).text
}
}
编译期效果:
groovyc --configscript=pathchecker.groovy ConfigService.groovy
若路径非法,控制台立即输出 编译期路径校验失败:文件 xxx 不存在,CI 流水线终止,零运行时风险。
拓展思考
- 多模块仓库场景:如何把路径校验做成 Gradle 插件,一次性注入到所有子工程的 compileGroovy 任务?
提示:实现PathExistsPlugin implements Plugin<Project>,在project.tasks.withType(GroovyCompile)里添加CompilationCustomizer。 - 动态路径无法常量折叠:如果路径是
System.getProperty("user.dir") + "/conf.yml",AST 转换阶段无法求值,可降级为编译期警告 + 运行时启动校验双保险。 - 与 Gradle 7+ 配置缓存兼容:自定义 AST 转换必须声明输入路径为 @PathSensitive(PathSensitivity.RELATIVE),否则配置缓存命中失败,导致国内大厂构建加速失效。