01 /**
02 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03 */
04 package net.sourceforge.pmd.lang.ast.xpath;
05
06 import java.lang.reflect.InvocationTargetException;
07 import java.lang.reflect.Method;
08
09 import net.sourceforge.pmd.lang.ast.Node;
10
11 /**
12 * @author daniels
13 */
14 public class Attribute {
15
16 private static final Object[] EMPTY_OBJ_ARRAY = new Object[0];
17 private Node parent;
18 private String name;
19 private Method method;
20 private Object value;
21 private String stringValue;
22
23 public Attribute(Node parent, String name, Method m) {
24 this.parent = parent;
25 this.name = name;
26 this.method = m;
27 }
28
29 public Attribute(Node parent, String name, String value) {
30 this.parent = parent;
31 this.name = name;
32 this.value = value;
33 this.stringValue = value;
34 }
35
36 public Object getValue() {
37 if (value != null) {
38 return value;
39 }
40 // this lazy loading reduces calls to Method.invoke() by about 90%
41 try {
42 return method.invoke(parent, EMPTY_OBJ_ARRAY);
43 } catch (IllegalAccessException iae) {
44 iae.printStackTrace();
45 } catch (InvocationTargetException ite) {
46 ite.printStackTrace();
47 }
48 return null;
49 }
50
51 public String getStringValue() {
52 if (stringValue != null) {
53 return stringValue;
54 }
55 Object v = this.value;
56 if (this.value == null) {
57 v = getValue();
58 }
59 if (v == null) {
60 stringValue = "";
61 } else {
62 stringValue = String.valueOf(v);
63 }
64 return stringValue;
65 }
66
67 public String getName() {
68 return name;
69 }
70
71 public Node getParent() {
72 return parent;
73 }
74
75 public String toString() {
76 return name + ":" + getValue() + ":" + parent;
77 }
78 }
|