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 import org.apache.commons.math.exception.util.LocalizedFormats; 024 025 /** 026 * A Default NumberTransformer for java.lang.Numbers and Numeric Strings. This 027 * provides some simple conversion capabilities to turn any java.lang.Number 028 * into a primitive double or to turn a String representation of a Number into 029 * a double. 030 * 031 * @version $Revision: 1073658 $ $Date: 2011-02-23 10:45:42 +0100 (mer. 23 f??vr. 2011) $ 032 */ 033 public class DefaultTransformer implements NumberTransformer, Serializable { 034 035 /** Serializable version identifier */ 036 private static final long serialVersionUID = 4019938025047800455L; 037 038 /** 039 * @param o the object that gets transformed. 040 * @return a double primitive representation of the Object o. 041 * @throws MathException if it cannot successfully be transformed. 042 * @see <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/Transformer.html">Commons Collections Transformer</a> 043 */ 044 public double transform(Object o) throws MathException { 045 if (o == null) { 046 throw new MathException(LocalizedFormats.OBJECT_TRANSFORMATION); 047 } 048 049 if (o instanceof Number) { 050 return ((Number)o).doubleValue(); 051 } 052 053 try { 054 return Double.valueOf(o.toString()).doubleValue(); 055 } catch (NumberFormatException e) { 056 throw new MathException(e, 057 LocalizedFormats.CANNOT_TRANSFORM_TO_DOUBLE, e.getMessage()); 058 } 059 } 060 061 /** {@inheritDoc} */ 062 @Override 063 public boolean equals(Object other) { 064 if (this == other) { 065 return true; 066 } 067 if (other == null) { 068 return false; 069 } 070 return other instanceof DefaultTransformer; 071 } 072 073 /** {@inheritDoc} */ 074 @Override 075 public int hashCode() { 076 // some arbitrary number ... 077 return 401993047; 078 } 079 080 }