3

In Java, would it be possible to implement a function that would take an object as input, and then convert the object to a type that is specified as a parameter?

I'm trying to implement a general-purpose type conversion function for primitive data types, but I don't know exactly where to start:

public static Object convertPrimitiveTypes(Object objectToConvert, String typeToConvertTo){
    //Given an object that is a member of a primitive type, convert the object to TypeToConvertTo, and return the converted object
}

For example, convertPrimitiveTypes(true, "String") would return the string "true", and convertPrimitiveTypes("10", "int") would return the integer 10. If the conversion were not well-defined (for example, converting a boolean to an integer), then the method would need to throw an exception, and terminate the program.

4

1 回答 1

8

我把它写成

public static <T> T convertTo(Object o, Class<T> tClass) {

如果乏味,这是可能的。如果您不关心效率,您可以转换为 String 并通过反射使用 "Class".valueOf(String) 。

public static void main(String... ignore) {
    int i = convertTo("10", int.class);
    String s = convertTo(true, String.class);
    BigDecimal bd = convertTo(1.2345, BigDecimal.class);
    System.out.println("i=" + i + ", s=" + s + ", bd=" + bd);
}

private static final Map<Class, Class> WRAPPER_MAP = new LinkedHashMap<Class, Class>();

static {
    WRAPPER_MAP.put(boolean.class, Boolean.class);
    WRAPPER_MAP.put(byte.class, Byte.class);
    WRAPPER_MAP.put(char.class, Character.class);
    WRAPPER_MAP.put(short.class, Short.class);
    WRAPPER_MAP.put(int.class, Integer.class);
    WRAPPER_MAP.put(float.class, Float.class);
    WRAPPER_MAP.put(long.class, Long.class);
    WRAPPER_MAP.put(double.class, Double.class);
}

public static <T> T convertTo(Object o, Class<T> tClass) {
    if (o == null) return null;
    String str = o.toString();
    if (tClass == String.class) return (T) str;
    Class wClass = WRAPPER_MAP.get(tClass);
    if (wClass == null) wClass = tClass;
    try {
        try {
            return (T) wClass.getMethod("valueOf", String.class).invoke(null, str);
        } catch (NoSuchMethodException e) {
            return (T) wClass.getConstructor(String.class).newInstance(str);
        }
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

印刷

i=10, s=true, bd=1.2345
于 2013-05-12T20:58:37.910 回答