Search code examples
javaspringspring-el

SpEL - get value from Object[]


I'm trying to write a SpEL expression that can search an Object[] array. Below is some sample code:

public class Foo {
    private String foo;
    public Foo(String foo) {
        this.foo = foo;
    }
    private String getFoo() {
        return foo;
    }
}

public class Bar {
    private String bar;
    public Bar(String bar) {
        this.bar = bar;
    }
    private String getBar() {
        return bar;
    }
}

    public static void main(String args) {
        Object arr[] = {new Foo("foo1"), new Bar("bar1")};
        ExpressionParser expressionParser = new SpelExpressionParser();
        Expression expression = expressionParser.parseExpression("someExpression to search for bar");
        Object expressionResult = expression.getValue(arr, Object.class);
    }

Can anybody help me write a SpEL to search arr and find the first object that has a property "bar" and return the value of bar?

The practical application of this is that I'm writing an annotation for an Aspect and I'm trying to declare the path to an argument in the annotation:

@MyAnnotation(spelPath="someExpression to search for bar")
public void myMethod(Foo foo, Bar bar, more arguments)

Your help is much appreciated!


Solution

  • The SpEL has reasonable limitations for the reflection. I would suggest to write some static utility method and call already it from the SpEL using a type operator:

    @MyAnnotation(spelPath="T(com.my.proj.MyUtils).searchBar(#root)")