当前位置: 首页 > 后端技术 > Java

后端国际化(三):使用AST完成中文转换和替换

时间:2023-04-02 10:00:04 Java

前言完成中文的抽取和过滤后,我们需要对中文节点进行转换、翻译和替换。文案转换文案转换通常有以下几种情况。普通的文案,比如“保存成功”,可以直接替换成相应的代码拼接文案“用户”+用户名+“不能为空”,占位符转换就完成了。合并成“用户{0}不能为空”,然后替换成对应代码注释中的文字。比如“Usercannotbeempty”,需要替换成对应的{code},需要在code两边加上{}才能满足要求。用I18nUtils.getMessage("save_succeeded")替换普通文本“保存成功”,用I18nUtils.getMessage(“user_name_not_empty”,newObject[]{user替换连接文本“用户名”+user.name+“不能为空”.name})注释中的文本@NotNull(message="'type'cannotbeempty")替换为@NotNull(message="{type_cannot_be_empty}")字段中的字符串privatestaticStringabc="Hello"将privateStringgetAbc(){returnI18nUtils.getMessage("hello")}MessageFormat.format中的文本替换为MessageFormat.format("Username{0}cannotbeempty",user.name)withI18nUtils.getMessage("user_name_not_empty",newObject[]{user.name})替换原理所谓替换就是解析对应的AST树,转换为目标树普通复制AST树构造MethodInvocationgetI18nCall(Listargs){defmethodInvocation=ast.newMethodInvocation()methodInvocation.setExpression(ast.newSimpleName(Config.getI18nClass()))methodInvocation.name=ast.newSimpleName("getMessage")methodInvocation.arguments().addAll(args)methodInvocation}复杂文本节点构建源AST树(MessageFormat.format(“{0}”,row))目标AST树(I18nUtils.getMessage(“{0}”,newObject[]{row}))voidreplaceMessageFormatWithI18n(MethodInvocationmethodInvocation,StringLiteralstringLiteral){defargs=[]//提取MessageFormat.format中的第一个中文StringLiteralcode=ASTNode.copySubtree(methodInvocation.getAST(),stringLiteral)//翻译并替换代码translateKey(code)//获取MessageFormat的其余部分。List的格式参数retainExp=methodInvocation.arguments().subList(1,methodInvocation.arguments().size()).collect({ASTNode.copySubtree(methodInvocation.getAST(),(ASTNode)it)})args.add(code)defarray=ast.newArrayCreation()args.add(array)//构造新对象节点array.setType(ast.newArrayType(ast.newSimpleType(ast.newSimpleName("Object"))))defarrayInitializer=ast.newArrayInitializer()//将剩余的所有参数添加到新的Object节点arrayInitializer.expressions().addAll(retainExp)array.setInitializer(arrayInitializer)//转换为I18nUtils.getMessage形式convertStringLiteral(args,methodInvocation)}

最新推荐
猜你喜欢