0

I am using reflections to map an ResultSet to a Field in bean.

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.

Dheerendra
  • 1,488
  • 5
  • 19
  • 36

3 Answers3

0

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.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
0

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. Doing

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

does not change that the referenced object is a String. In your case, you'll probably need a conversion strategy to convert between types.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

You still have another option, convert long to string ,and then convert to integer.

Frank ZHENG
  • 109
  • 5