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 package org.apache.commons.jxpath.util; 18 19 import java.util.HashMap; 20 21 /** 22 * Global type conversion utilities. 23 * 24 * @author Dmitri Plotnikov 25 * @version $Revision: 652845 $ $Date: 2008-05-02 19:46:46 +0200 (Fr, 02 Mai 2008) $ 26 */ 27 public class TypeUtils { 28 private static TypeConverter typeConverter = new BasicTypeConverter(); 29 private static final HashMap PRIMITIVE_TYPE_MAP = new HashMap() { 30 { 31 put(int.class, Integer.class); 32 put(byte.class, Byte.class); 33 put(short.class, Short.class); 34 put(char.class, Character.class); 35 put(long.class, Long.class); 36 put(float.class, Float.class); 37 put(double.class, Double.class); 38 put(boolean.class, Boolean.class); 39 } 40 }; 41 42 /** 43 * Install an alternative type converter. 44 * @param converter new TypeConverter 45 */ 46 public static synchronized void setTypeConverter(TypeConverter converter) { 47 typeConverter = converter; 48 } 49 50 /** 51 * Returns the current type converter. 52 * @return TypeConverter 53 */ 54 public static TypeConverter getTypeConverter() { 55 return typeConverter; 56 } 57 58 /** 59 * Returns true if the global converter can convert the supplied 60 * object to the specified type. 61 * @param object object to test 62 * @param toType target class 63 * @return boolean 64 */ 65 public static boolean canConvert(Object object, Class toType) { 66 return typeConverter.canConvert(object, toType); 67 } 68 69 /** 70 * Converts the supplied object to the specified type. May 71 * throw a RuntimeException. 72 * @param object object to convert 73 * @param toType target class 74 * @return resulting Object 75 */ 76 public static Object convert(Object object, Class toType) { 77 return typeConverter.convert(object, toType); 78 } 79 80 /** 81 * Return the appropriate wrapper type for the specified class. 82 * @param p Class for which to retrieve a wrapper class. 83 * @return the wrapper if <code>p</code> is primitive, else <code>p</code>. 84 * @since JXPath 1.3 85 */ 86 public static Class wrapPrimitive(Class p) { 87 return p.isPrimitive() ? (Class) PRIMITIVE_TYPE_MAP.get(p) : p; 88 } 89 }