Java实现占位符替换对象参数

实现效果

${address}今天${status}!  ==》  长沙今天天晴!

实现代码

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 占位符替换工具类
 */
public class PlaceHolderUtil {
    private static final Pattern pattern = Pattern.compile("\\$\\{.*?\\}");
    private static Matcher matcher;

    /**
     * 替换字符串占位符, 字符串中使用${key}表示占位符
     * 利用反射 自动获取对象属性值 (必须有get方法)
     *
     * @param sourceString 需要匹配的字符串
     * @param obj        参数对象
     * @return
     */
    public static <T> String replaceWithObject(String sourceString, T obj) {

        String targetString = sourceString;

        /**
         * PropertyDescriptor类:(属性描述器)
         *   PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
         *   1. getPropertyType(),获得属性的Class对象;
         *   2. getReadMethod(),获得用于读取属性值的方法;
         *   3. getWriteMethod(),获得用于写入属性值的方法;
         *   4. hashCode(),获取对象的哈希值;
         *   5. setReadMethod(Method readMethod),设置用于读取属性值的方法;
         *   6. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
         */
        PropertyDescriptor pd;

        /**
         * getName() 获取方法名
         * isVarArgs() 如果该方法声明为采用可变数量的参数,则返回true; 否则返回false
         * getModifiers() 获取权限修饰符
         * getReturnType() 获取返回类型
         * getExceptionTypes() 获取所有抛出的异常类型
         * getGenericReturnType() 返回Type类型
         * getParameterTypes() 获取所有参数的类型
         * getParameterCount() 获取所有参数的个数
         * getAnnotations() 获取方法级别的注解
         * getDeclaringClass() 获取方法所在的类信息
         */
        Method getMethod;

        // 匹配${}中间的内容
        // 当正则完全匹配字符串,从头到尾正好匹配上字符串,matches()方法是true,find()方法为false
        // 当正则只能匹配字符串中的部分内容,matches()方法是fasle,find()方法是true
        matcher = pattern.matcher(sourceString);
        while (matcher.find()) {
            String key = matcher.group();
            String holderName = key.substring(2, key.length() - 1).trim();
            try {
                pd = new PropertyDescriptor(holderName, obj.getClass());
                getMethod = pd.getReadMethod(); // 获得get方法
                Object value = getMethod.invoke(obj);
                if (value != null) {
                    targetString = targetString.replace(key, value.toString());
                }
            } catch (Exception e) {
                throw new RuntimeException("propertyDescriptor failed", e);
            }
        }
        return targetString;
    }
}
public class Local {
    private String address;
    private String status;

    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
}
public class test {
    public static void main(String[] args) {
        Local address = new Local();
        address.setAddress("长沙");
        address.setStatus("晴天");
        String text = PlaceHolderUtil.replaceWithObject("${address}今天${status}!",address);
        System.out.println(text);
    }
}

输出结果

长沙今天晴天!

Process finished with exit code 0

你可能感兴趣的:(Java)