Good question. I was also interested last night;)
So the answer is that there are two different types of polymorphism: compilation and run-time polymorphism.
When you use the supertype method and the overridden sybtypes methods, this is polymorphism at runtime.
When you use super types and subtypes as parameters for different overloaded methods, this is a compile-time polymorphism.
Therefore, the compiler, in your case, must know at compile time which method (/ overload) to execute, it will not make this decision at runtime.
If you had control over the field class, then the solution would be to use generics so that you define
class Field<T>
using method
T get( Object o )
Then the compiler will be able to find out at compile time which method to use to display, as he would know, at compile time, what type field.get returns.
But according to your comments, you are using the java.lang.reflect.Field JDK class and therefore you have no control over it to make it shared. In this case, yes, the only solution is a mapping method that handles all the various possible types for field.get. But really, the String.valueOf method could help a lot here, since it provides a string representation of any type in java, it is already doing the overload job you're looking for.
The source is here .
Regards, StΓ©phane
source share