我只想使用SpEL从Tester对象列表中获取ID列表
List<Tester> tests = new ArrayList<Tester>();
tests.add(new Tester(1)); ...
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("tests",tests);
System.out.println(tests.stream().map(Tester::getId).collect(Collectors.toList())); // LIKE THIS
System.out.println(parser.parseExpression("#tests what to write here").getValue(context));
所需结果:[1、2、3、4]
测试器是
public class Tester {
private Integer id;
}
答案 0 :(得分:1)
答案 1 :(得分:0)
这是一种肮脏的方式:
public class ParseCheck {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
List<Tester> tests = Arrays.asList(new Tester(1),new Tester(2),new Tester(3),new Tester(4),new Tester(1));
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction("stream", ParseCheck.class.getMethod("stream", String.class));
context.setVariable("tests",tests);
System.out.println(tests.stream().map(Tester::getId).distinct().collect(Collectors.toList()));
System.out.println(parser.parseExpression("#tests.stream().map(#stream('id')).distinct().collect(T(java.util.stream.Collectors).toList())").getValue(context));
}
public static Function<Object, Object> stream(String property) {
ExpressionParser parser = new SpelExpressionParser();
return s -> parser.parseExpression(property).getValue(s);
}
}
此处在上下文中注册了一个函数,该函数将返回需要提取的属性流。该属性也是使用SpEL提取的。