实现一个简单的占位符${}替换

今天看到占位符,心血来潮,想自己实现一个简单的试试:

package com.ccm.templateproject.entity;

import lombok.Data;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Data
public class Action {
    private String name;
    private String address;
    private String doSomething;

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        String s = "${name}去了${address}${doSomething}";
        Action action = new Action();
        action.setName("张梦婷");
        action.setAddress("医院");
        action.setDoSomething("看了妈妈");
        System.out.println(parse(s,action));;
    }

    public static <T> String parse(String content,T t) throws NoSuchFieldException, IllegalAccessException {
        Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()){
            //获取匹配到的字段名
            String fieldName = matcher.group(1);
            Field field = t.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            //要替换的子串
            String replace = matcher.group(0);
            content = content.replace(replace, (String)field.get(t));
        }
        return content;
    }
}

看到输出,小小满足,收工!!!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容