dimanche 4 juillet 2021

In Java, how can I cast a field to its declaring type?

If I have a Field and I know that the type of the field was declared as an Integer for example, I can get and cast the object using (Integer) field.get(someObj) (I'm aware the field class has special "get" methods for different primitive types, but it's just an example). Is there any way to generalize this and retrieve the field value and then cast it to whatever the field's declaring class is? I know I can retrieve the declaring class using field.getDeclaringClass(), but how can I then use that to cast the result of field.get(someObj) to that class?





Aucun commentaire:

Enregistrer un commentaire