Here you can find the source of convertTo(Class> clazz, Object obj)
public static Comparable<?> convertTo(Class<?> clazz, Object obj)
//package com.java2s; /******************************************************************************* * Copyright (c)2014 Prometheus Consulting * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License.// w w w . j ava 2 s . c o m *******************************************************************************/ import java.math.BigDecimal; public class Main { public static Comparable<?> convertTo(Class<?> clazz, Object obj) { if (obj == null) { return null; } if (clazz.isAssignableFrom(obj.getClass())) { return (Comparable<?>) obj; } if (clazz.isPrimitive()) { if (clazz.equals(Long.TYPE)) { clazz = Long.class; } else if (clazz.equals(Integer.TYPE)) { clazz = Integer.class; } else if (clazz.equals(Float.TYPE)) { clazz = Float.class; } else if (clazz.equals(Double.TYPE)) { clazz = Double.class; } else if (clazz.equals(Boolean.TYPE)) { clazz = Boolean.class; } } if (Number.class.isAssignableFrom(clazz)) { if (obj.getClass().equals(String.class)) { obj = new Double((String) obj); } if (!Number.class.isAssignableFrom(obj.getClass())) { throw new RuntimeException( "Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName()); } Number number = (Number) obj; if (clazz.equals(Long.class)) { return new Long(number.longValue()); } if (clazz.equals(Integer.class)) { return new Integer(number.intValue()); } if (clazz.equals(Float.class)) { return new Float(number.floatValue()); } if (clazz.equals(Double.class)) { return new Double(number.doubleValue()); } if (clazz.equals(BigDecimal.class)) { return new BigDecimal(number.doubleValue()); } } final String oStr = String.valueOf(obj); if (clazz.equals(String.class)) { return oStr; } if (clazz.equals(java.util.Date.class)) { return java.sql.Date.valueOf(oStr); } if (clazz.equals(java.sql.Date.class)) { return java.sql.Date.valueOf(oStr); } if (clazz.equals(Boolean.class)) { return new Boolean(oStr); } throw new RuntimeException("Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName()); } }