View Javadoc
1   package org.codehaus.plexus.interpolation;
2   
3   /*
4    * Copyright 2007 The Codehaus Foundation.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor;
20  
21  /**
22   * Wraps an object, providing reflective access to the object graph of which the
23   * supplied object is the root. Expressions like 'child.name' will translate into
24   * 'rootObject.getChild().getName()' for non-boolean properties, and
25   * 'rootObject.getChild().isName()' for boolean properties.
26   */
27  public class ObjectBasedValueSource
28      extends AbstractValueSource
29  {
30  
31      private final Object root;
32  
33      /**
34       * Construct a new value source, using the supplied object as the root from
35       * which to start, and using expressions split at the dot ('.') to navigate
36       * the object graph beneath this root.
37       * @param root the root of the graph.
38       */
39      public ObjectBasedValueSource( Object root )
40      {
41          super( true );
42          this.root = root;
43      }
44  
45      /**
46       * <p>Split the expression into parts, tokenized on the dot ('.') character. Then,
47       * starting at the root object contained in this value source, apply each part
48       * to the object graph below this root, using either 'getXXX()' or 'isXXX()'
49       * accessor types to resolve the value for each successive expression part.
50       * Finally, return the result of the last expression part's resolution.</p>
51       * 
52       * <p><b>NOTE:</b> The object-graph nagivation actually takes place via the
53       * {@link ReflectionValueExtractor} class.</p>
54       */
55      public Object getValue( String expression )
56      {
57          if ( expression == null || expression.trim().length() < 1 )
58          {
59              return null;
60          }
61          
62          try
63          {
64              return ReflectionValueExtractor.evaluate( expression, root, false );
65          }
66          catch ( Exception e )
67          {
68              addFeedback( "Failed to extract \'" + expression + "\' from: " + root, e );
69          }
70  
71          return null;
72      }
73  
74  }