View Javadoc

1   /*
2    * Copyright 1999-2004 The Apache Software Foundation
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.commons.jxpath.ri.compiler;
17  
18  import org.apache.commons.jxpath.ri.EvalContext;
19  
20  /***
21   * A compile tree element containing a constant number or string.
22   *
23   * @author Dmitri Plotnikov
24   * @version $Revision: 1.8 $ $Date: 2004/02/29 14:17:39 $
25   */
26  public class Constant extends Expression {
27  
28      private Object value;
29  
30      public Constant(Number number) {
31          this.value = number;
32      }
33  
34      public Constant(String string) {
35          this.value = string;
36      }
37  
38      public Object compute(EvalContext context) {
39          return value;
40      }
41  
42      /***
43       * Returns the value of the constant.
44       */
45      public Object computeValue(EvalContext context) {
46          return value;
47      }
48  
49      /***
50       * Returns false
51       */
52      public boolean isContextDependent() {
53          return false;
54      }
55  
56      /***
57       * Returns false
58       */
59      public boolean computeContextDependent() {
60          return false;
61      }
62  
63      public String toString() {
64          if (value instanceof Number) {
65              double doubleValue = ((Number) value).doubleValue();
66              long longValue = ((Number) value).longValue();
67              if (doubleValue == longValue) {
68                  return String.valueOf(longValue);
69              }
70              else {
71                  return String.valueOf(doubleValue);
72              }
73          }
74          else {
75              return "'" + value + "'";
76          }
77      }
78  }