All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.spitmaster.warlock.util.SpelExpressionUtil Maven / Gradle / Ivy

Go to download

warlock-spring-boot-starter is an annotation-driven concurrency tools library for java with Spring. It is easy to use in Spring application Just using annotation on your method , the concurrency lock problem would be solved

There is a newer version: 1.0.1
Show newest version
package io.github.spitmaster.warlock.util;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Array;
import java.lang.reflect.Method;

public class SpelExpressionUtil {
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    public static  T parseSpel(Method targetMethod, Object[] args, String spel, Class paramType) {
        EvaluationContext context = new StandardEvaluationContext();
        LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames = discoverer.getParameterNames(targetMethod);
        if (paramNames == null || Array.getLength(paramNames) == 0) {
            return null;
        }

        for (int len = 0; len < paramNames.length; ++len) {
            context.setVariable(paramNames[len], args[len]);
        }

        if (isBlank(spel)) {
            return null;
        } else {
            Expression expression = PARSER.parseExpression(spel);
            return expression.getValue(context, paramType);
        }
    }

    //copied from org.apache.commons.lang3.StringUtils#isBlank
    private static boolean isBlank(final CharSequence cs) {
        final int strLen = cs == null ? 0 : cs.length();
        if (strLen == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (!Character.isWhitespace(cs.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy