// 示例代码:使用Spring Expression Language (SpEL) 进行表达式求值
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class SpelExample {
public static void main(String[] args) {
// 创建一个表达式解析器
ExpressionParser parser = new SpelExpressionParser();
// 简单的字符串拼接表达式
String expression = " 'Hello, ' + 'World!' ";
String result = parser.parseExpression(expression).getValue(String.class);
System.out.println(result); // 输出: Hello, World!
// 使用上下文进行表达式求值
StandardEvaluationContext context = new StandardEvaluationContext();
Person person = new Person("John", 30);
context.setVariable("person", person);
// 访问对象属性
expression = "person.name";
String name = parser.parseExpression(expression).getValue(context, String.class);
System.out.println(name); // 输出: John
// 执行方法调用
expression = "person.getAge()";
Integer age = parser.parseExpression(expression).getValue(context, Integer.class);
System.out.println(age); // 输出: 30
}
// 辅助类
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
SpelExpressionParser
来解析 SpEL 表达式。StandardEvaluationContext
设置变量和对象,以便在表达式中引用它们。person.name
)。person.getAge()
)。上一篇:java求绝对值
下一篇:java file 转 byte
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站