I’m saving a properties file by using reflection to loop through a class’s fields one by one and saving the field’s name and value to the file.
Now I need to create this class again and give it the values stored in the properties file. I came up with this. returnEntity is the new instance of the class.
for (Field f : returnEntity.getClass().getFields())
{
Class fieldType = f.getType();
String fieldName = f.getName();
f.set(returnEntity, fieldType.cast(properties.get(fieldName)));
}
It works up until it has to cast the field to the type “Int”. For some reason it throws a ClassCastException then. What am I doing wrong?
The problem is that int is not a class, like, float, char, short, long, they are all primitives. To make this work you need to cast to Integer, then use intValue();