java 模板语言_java-如何使用表达式语言解析模板化句子“...

Is there any way to achieve this?

我不是100%肯定我了解您的要求,但是这里有一些提示…

如果您有一些属性,并且想要搜索和替换形状为#{property.key}的子字符串,您也可以这样做:

import java.util.Properties;

import java.util.regex.*;

class Test {

public static String process(String template, Properties props) {

Matcher m = Pattern.compile("#\{(.*?)\}").matcher(template);

StringBuffer sb = new StringBuffer();

while (m.find())

m.appendReplacement(sb, props.getProperty(m.group(1).trim()));

m.appendTail(sb);

return sb.toString();

}

public static void main(String[] args) {

Properties props = new Properties();

props.put("user.name", "Jon");

props.put("user.email", "jon.doe@example.com");

String template = "Name: #{ user.name }, email: #{ user.email }";

// Prints "Name: Jon, email: jon.doe@example.com"

System.out.println(process(template, props));

}

}

如果您有实际的POJO而不是Properties对象,则可以进行反射,如下所示:

import java.util.regex.*;

class User {

String name;

String email;

}

class Test {

public static String process(String template, User user) throws Exception {

Matcher m = Pattern.compile("#\{(.*?)\}").matcher(template);

StringBuffer sb = new StringBuffer();

while (m.find()) {

String fieldId = m.group(1).trim();

Object val = User.class.getDeclaredField(fieldId).get(user);

m.appendReplacement(sb, String.valueOf(val));

}

m.appendTail(sb);

return sb.toString();

}

public static void main(String[] args) throws Exception {

User user = new User();

user.name = "Jon";

user.email = "jon.doe@example.com";

String template = "Name: #{ name }, email: #{ email }";

System.out.println(process(template, user));

}

}

…但是它变得越来越丑陋,我建议您考虑更深入地研究一些第三方库来解决此问题.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值