Here you can find the source of convertTo(final Class
public static Comparable<?> convertTo(final Class<Comparable<?>> 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 a v a2 s. c om*/ *******************************************************************************/ import java.math.BigDecimal; public class Main { public static Comparable<?> convertTo(final Class<Comparable<?>> clazz, Object obj) { if (obj == null) { return null; } if (clazz.isAssignableFrom(obj.getClass())) { return (Comparable<?>) obj; } final String oStr = String.valueOf(obj); if (clazz.equals(String.class)) { return oStr; } if (clazz.equals(Long.class) || clazz.equals(Long.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Long(((Number) obj).longValue()); } return Long.valueOf(oStr); } if (clazz.equals(Integer.class) || clazz.equals(Integer.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Integer(((Number) obj).intValue()); } return Integer.valueOf(oStr); } if (clazz.equals(Double.class) || clazz.equals(Double.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Double(((Number) obj).doubleValue()); } return Double.valueOf(oStr); } if (clazz.equals(Float.class) || clazz.equals(Float.TYPE)) { if (Number.class.isAssignableFrom(obj.getClass())) { return new Float(((Number) obj).floatValue()); } return Float.valueOf(oStr); } if (clazz.equals(BigDecimal.class)) { return new BigDecimal(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); } return null; } public static boolean equals(final Object o, final Object o1) { if (o == null && o1 == null) { return true; } if (o == null || o1 == null) { return false; } if (o instanceof Number && o1 instanceof Number) { return ((Number) o).doubleValue() == ((Number) o1).doubleValue(); } return o.equals(o1); } }