dimanche 16 février 2020

How to set a Number field with a different Number type using Java Reflection

Our original code is something like:

Object bean = ...
Field field = ...
Object value = ... // Retrieved from Database
field.set(bean, value);

But the type of bean field may be different from type of value, e.g. our bean is an Integer but value retrieved from db may be Byte or Short.

How can I write some simple code to convert boxed types without reflection exception?

Here is my solution but not as simple as my expectation:

if (field.getType().equals(Integer.class)) {
   field.set(bean, Integer.valueOf(((Number) value).intValue()));
} else if (field.getType().equals(Short.class)) {
   field.set(bean, Short.valueOf(((Number) value).shortValue()));
} else if (...) {
   ...
}




Aucun commentaire:

Enregistrer un commentaire