LoginSignup
4
5

More than 5 years have passed since last update.

ドットでつながれたプロパティ名で指定された値をサクっと取得する方法

Last updated at Posted at 2015-04-17

"foo.bar.baz" みたいな文字列で getFoo().getBar().getBaz() によって得られる値を取得します。

Spring の使用が前提ですが、SpEL を利用することで簡単に取得できます。

SpelExpressionParser parser = new SpelExpressionParser();
Expression expr = parser.parseExpression("foo.bar.baz");
Object value = expr.getValue(bean);

これだけ。

StandardEvaluationContext を用意して、MapAccessor を設定しておけば Map オブジェクトに対しても同様にアクセスできます。

StandardEvaluationContext context = new StandardEvaluationContext();
context.addPropertyAccessor(new MapAccessor());

Object value = expr.getValue(context, map);
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5