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 extends AbstractValueSource { 28 29 private final Object root; 30 31 /** 32 * Construct a new value source, using the supplied object as the root from 33 * which to start, and using expressions split at the dot ('.') to navigate 34 * the object graph beneath this root. 35 * @param root the root of the graph. 36 */ 37 public ObjectBasedValueSource(Object root) { 38 super(true); 39 this.root = root; 40 } 41 42 /** 43 * <p>Split the expression into parts, tokenized on the dot ('.') character. Then, 44 * starting at the root object contained in this value source, apply each part 45 * to the object graph below this root, using either 'getXXX()' or 'isXXX()' 46 * accessor types to resolve the value for each successive expression part. 47 * Finally, return the result of the last expression part's resolution.</p> 48 * 49 * <p><b>NOTE:</b> The object-graph nagivation actually takes place via the 50 * {@link ReflectionValueExtractor} class.</p> 51 */ 52 public Object getValue(String expression) { 53 if (expression == null || expression.trim().length() < 1) { 54 return null; 55 } 56 57 try { 58 return ReflectionValueExtractor.evaluate(expression, root, false); 59 } catch (Exception e) { 60 addFeedback("Failed to extract \'" + expression + "\' from: " + root, e); 61 } 62 63 return null; 64 } 65 }