简体   繁体   English

Java反射:在不知道对象类型的情况下将其转换为另一个对象

[英]Java Reflection: Casting an Object to another without knowing their types

I am using reflections to map an ResultSet to a Field in bean. 我正在使用反射将ResultSet映射到bean中的Field

field = clazz.getDeclaredField(str);
field.setAccessible(true);
Object resultSetObject = rs.getObject(str);
Class fieldType = field.getType();
field.set(clazzInst, fieldType.cast(resultSetObject));

The problem is resultSetObject is of type Integer and fieldType is of Long and I cannot cast Intger to Long and getting ClassCastException . 问题是resultSetObject的类型为IntegerfieldType的类型为Long,我无法将Intger转换为Long并获取ClassCastException

You are essentially asking to duplicate the type knowledge that is available at compile-time with which the compiler generates the correct conversion. 实质上,您是在要求复制在编译时可用的类型知识,编译器利用这些知识来生成正确的转换。 The runtime doesn't have this knowledge, so you will have to provide it by building a matrix of types and coding all the conversions you want, explicitly. 运行时不具备这些知识,因此您将必须通过构建类型矩阵并明确编码所需的所有转换来提供它。

You can define this as a matrix indexed by type along both axes (from-type and to-type) or more likely as a Map whose key is a ConversionType object each instance of which defines fromType , toType and a convert() method. 您可以将其定义为沿两个轴(从类型和到类型)按类型索引的矩阵,也可以将其定义为Map,其键为ConversionType对象,每个实例的实例都定义fromTypetoTypeconvert()方法。

Whether you have 是否有

Object ref = new String("object of type string");

or 要么

String ref = new String("still object of type string");

the object referenced will be of type String . 引用的对象将为String类型。 Doing 在做

Object obj = (Object) new String("still a string");

does not change that the referenced object is a String . 不会更改引用的对象是String In your case, you'll probably need a conversion strategy to convert between types. 就您而言,您可能需要一种转换策略来在类型之间进行转换。

您还有另一个选择,将long转换为string,然后转换为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM