001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 package org.apache.commons.math.util;
019
020 import java.io.Serializable;
021
022 import org.apache.commons.math.MathException;
023
024 /**
025 * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This
026 * provides some simple conversion capabilities to turn any java.lang.Number
027 * into a primitive double or to turn a String representation of a Number into
028 * a double.
029 *
030 * @version $Revision: 811685 $ $Date: 2009-09-05 13:36:48 -0400 (Sat, 05 Sep 2009) $
031 */
032 public class DefaultTransformer implements NumberTransformer, Serializable {
033
034 /** Serializable version identifier */
035 private static final long serialVersionUID = 4019938025047800455L;
036
037 /**
038 * @param o the object that gets transformed.
039 * @return a double primitive representation of the Object o.
040 * @throws org.apache.commons.math.MathException If it cannot successfully
041 * be transformed or is null.
042 * @see <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html"/>
043 */
044 public double transform(Object o) throws MathException{
045
046 if (o == null) {
047 throw new MathException("Conversion Exception in Transformation, Object is null");
048 }
049
050 if (o instanceof Number) {
051 return ((Number)o).doubleValue();
052 }
053
054 try {
055 return Double.valueOf(o.toString()).doubleValue();
056 } catch (NumberFormatException e) {
057 throw new MathException(e,
058 "Conversion Exception in Transformation: {0}", e.getMessage());
059 }
060 }
061
062 /** {@inheritDoc} */
063 @Override
064 public boolean equals(Object other) {
065 if (this == other) {
066 return true;
067 }
068 if (other == null) {
069 return false;
070 }
071 return other instanceof DefaultTransformer;
072 }
073
074 /** {@inheritDoc} */
075 @Override
076 public int hashCode() {
077 // some arbitrary number ...
078 return 401993047;
079 }
080
081 }