【发布时间】:2013-05-12 20:55:27
【问题描述】:
在Java中,是否有可能实现一个将对象作为输入的函数,然后将对象转换为指定为参数的类型?
我正在尝试为原始数据类型实现一个通用的类型转换函数,但我不知道从哪里开始:
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
}
例如,convertPrimitiveTypes(true, "String") 将返回字符串 "true",convertPrimitiveTypes("10", "int") 将返回整数 10。如果转换没有明确定义(例如,将布尔值转换为整数),则方法需要抛出异常,并终止程序。
【问题讨论】:
-
(many) switch + (many) instanceof?
-
您的方法接受
Object并返回Object。不涉及原语。 -
您没有指定要转换的输入类型。
-
@Brandon 该方法没有指定要转换的类型。它指定要转换的对象,以及要转换的对象的类型。
-
Object我假设您的意思是将原始类型的包装类发送到函数?