KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > math > util > DefaultTransformer


1 /*
2  * Copyright 2003-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
17 package org.apache.commons.math.util;
18
19 import java.io.Serializable JavaDoc;
20
21 import org.apache.commons.math.MathException;
22
23 /**
24  * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This
25  * provides some simple conversion capabilities to turn any java/lang.Number
26  * into a primitive double or to turn a String representation of a Number into
27  * a double.
28  *
29  * @version $Revision$ $Date: 2005-02-26 05:11:52 -0800 (Sat, 26 Feb 2005) $
30  */

31 public class DefaultTransformer implements NumberTransformer, Serializable JavaDoc {
32     
33     /** Serializable version identifier */
34     static final long serialVersionUID = 4019938025047800455L;
35     
36     /**
37      * @param o the object that gets transformed.
38      * @return a double primitive representation of the Object o.
39      * @throws org.apache.commons.math.MathException If it cannot successfully
40      * be transformed or is null.
41      * @see org.apache.commons.collections.Transformer#transform(java.lang.Object)
42      */

43     public double transform(Object JavaDoc o) throws MathException{
44
45         if (o == null) {
46             throw new MathException("Conversion Exception in Transformation, Object is null");
47         }
48
49         if (o instanceof Number JavaDoc) {
50             return ((Number JavaDoc)o).doubleValue();
51         }
52             
53         try {
54             return new Double JavaDoc(o.toString()).doubleValue();
55         } catch (Exception JavaDoc e) {
56             throw new MathException("Conversion Exception in Transformation: " + e.getMessage(), e);
57         }
58     }
59 }
Popular Tags