But indeed, the String.valueOf method could greatly help here as it provides a string representation of any type in java, already does the overload job you are looking for. In this case, yes, the only solution is to have a display method that handles all the different possible types for field.get. Then the compiler would be able to know, at compile time, which method to use for display as it would know, at compile-time, what type is returned by field.get.īut, according to your comments, you use the JDK's class and thus, you have no control over it to make it generic. If you would have Control over the field class, then a solution would be to use generics so that you define a class Field So the compiler, in your case, has to know at compile-time which method(/overload) to execute, it won't take this decision at run-time. When you use a super types and sub types as parameters for different overloaded methods, this is compile-time polymorphism. When you use a method of a supertype and the overriden methods of sybtypes, this is run-time polymorphism. So the answer is that there are 2 different types of polymorphism : compile-time and run-time polymorphism. In order to achieve this, we used one keyword named as ‘Override’ the method should be annotated with this annotation. Thanks in advance, good people from StackOverflow! In OOPS, we can achieve run time polymorphism by the use of method overriding, which means it should be achieved when the two-class have some relationship mostly it is inheritance. This does however seem ugly, and I was wondering if there was a more elegant way to make sure the right method is called. (Other primitive types and arrays omitted for simplicity's sake.)Įventhough Field's get method returns an Object, I thought the right methods would be called for the primitive type wrappers (Integers, Strings, etc.), but actually, only display(Object o) is called (no implicit downcasting is performed).įor now, the only solution I have found is to brutally downcast the objects if possible like this: public static void display(Object o) ("A " + o.getClass() + " which is composed of:") Basically a method for each primitive type wrapper This allows us to perform a single action in different ways. Polymorphism uses those methods to perform different tasks. Like we specified in the previous chapter Inheritance lets us inherit fields and methods from another class. I am using the getFields() method to iterate on the different attributes and display the object contents: public static void display(Integer i) Polymorphism means 'many forms', and it occurs when we have many classes that are related to each other by inheritance. I am playing with Java's reflection API, and I'm writing methods that inspect a given object and describes its fields, methods, and so on.
0 Comments
Leave a Reply. |