1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.commons.math.util; 19 20 import java.io.Serializable; 21 22 import org.apache.commons.math.MathException; 23 import org.apache.commons.math.exception.util.LocalizedFormats; 24 25 /** 26 * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This 27 * provides some simple conversion capabilities to turn any java.lang.Number 28 * into a primitive double or to turn a String representation of a Number into 29 * a double. 30 * 31 * @version $Revision: 1073658 $ $Date: 2011-02-23 10:45:42 +0100 (mer. 23 fvr. 2011) $ 32 */ 33 public class DefaultTransformer implements NumberTransformer, Serializable { 34 35 /** Serializable version identifier */ 36 private static final long serialVersionUID = 4019938025047800455L; 37 38 /** 39 * @param o the object that gets transformed. 40 * @return a double primitive representation of the Object o. 41 * @throws MathException if it cannot successfully be transformed. 42 * @see <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html">Commons Collections Transformer</a> 43 */ 44 public double transform(Object o) throws MathException { 45 if (o == null) { 46 throw new MathException(LocalizedFormats.OBJECT_TRANSFORMATION); 47 } 48 49 if (o instanceof Number) { 50 return ((Number)o).doubleValue(); 51 } 52 53 try { 54 return Double.valueOf(o.toString()).doubleValue(); 55 } catch (NumberFormatException e) { 56 throw new MathException(e, 57 LocalizedFormats.CANNOT_TRANSFORM_TO_DOUBLE, e.getMessage()); 58 } 59 } 60 61 /** {@inheritDoc} */ 62 @Override 63 public boolean equals(Object other) { 64 if (this == other) { 65 return true; 66 } 67 if (other == null) { 68 return false; 69 } 70 return other instanceof DefaultTransformer; 71 } 72 73 /** {@inheritDoc} */ 74 @Override 75 public int hashCode() { 76 // some arbitrary number ... 77 return 401993047; 78 } 79 80 } 81